2016-07-22 48 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()」是做什麼的。 –