2016-07-22 44 views
0

在我的反应成分我打电话的动作ComponentDidMount()这样的:reactjs发出后的特定时间内连续答应

componentDidMount() { 
     const { actions } = this.props 

     function save_project_continiously() { 
      console.log("inside") 
      actions.save_project().then(save_project_continiously) 
     } 

     save_project_continiously() 
    } 

在这里,我呼吁连续的动作。我的行为是这样的:

export function save_project() { 
    return (dispatch, getState) => { 

     setTimeout(() => { 
      return dispatch(manage_data()).then(response => { 
       console.log("Hellooww world") 
       return response 
      }) 
     }, 3000) 
    } 
} 

当我做到这一点给了我错误说.then()不是ComponentDidMount()功能..

如果我做

export function save_project() { 
     return (dispatch, getState) => { 

      return dispatch(manage_data()).then(response => { 
       console.log("Hellooww world") 
       return response 
      }) 
     } 
    } 

它被连续调用,但我希望它在特定时间后连续调用。

我尝试这样做:

export function save_project() { 
     return (dispatch, getState) => { 
      return new Promise((resolve, reject) => { 
       setTimeout(() => { 
        return dispatch(manage_data()).then(response => { 
         console.log("Hellooww world") 
         return response 
        }) 
       }, 3000) 
      }) 
     } 
    } 

但它仅调用一次..不给任何错误,但它仅调用一次..

我想是我想时间可持续叫行动在完成行动后的特定时间之后。

在这里,我想打电话给save_project和完成之后,我再次想将它在3秒钟后,不断去..

我怎样才能做到这一点?

有什么建议?

在此先感谢

回答

1

在这段代码中,你在包装允诺,但你真正想要做的是对成功的承诺,决心再次执行该代码。

export function save_project() { 
    // So this code does return callback, so it does not return promise 
    // in your first example. 
    return (dispatch, getState) => { 
     // Then this code returns promise, but it never gets resolved. 
     return new Promise((resolve, reject) => { 
      setTimeout(() => { 
       // Then you return promise from set timeout, but it 
       // is doubtful as well 
       return dispatch(manage_data()).then(response => { 
        console.log("Hellooww world") 
        return response 
       }) 
      }, 3000) 
     }) 
    } 
} 

你真正想要做的是:

// Just return promise of dispatch instead of wrapping it in 
// a callback. 
export function save_project() { 
    return dispatch(manage_data()); 
} 

// Then use set timeout here 
function save_project_continiously() { 
    console.log("inside") 
    actions.save_project().then(() => { 
     setTimeout(save_project_continiously, 3000); 
    }); 
} 

或者,如果你真的想在save_project回调,你需要在你的榜样他们undefined反正适当ARGS正确地调用它。

0

尝试setInterval()

export function save_project() { 
    return new Promise((resolve, reject) => { 
    setTimeout(() => { 
     dispatch(manage_data()).then(response => { 
     resolve(response); 
     }, error => { 
     reject(response); 
     }) 
    }, 3000) 
    }); 
} 
+0

这将每3秒钟调用一次。但我的'管理'数据可能需要10秒才能执行..我想要的是'save_project'应该在3秒后才能被调用,只有当'manage_data'已经成功完成时。这个工作是否会更新我的答案 – gamer

+0

。如果这不起作用,我很抱歉,但你的代码很混乱。根本不清楚“dispatch”或“manage_data()”是做什么的。 –