Reactjs 我如何在redux操作分派调用中返回承诺,以便链接。然后阻止?

Reactjs 我如何在redux操作分派调用中返回承诺,以便链接。然后阻止?,reactjs,react-native,promise,Reactjs,React Native,Promise,我正在使用react native和redux创建一个应用程序。我的应用程序应该向firebase rest api发送请求,以获取用户的todo。在我的react本机应用程序中,我通过react本机组件的connect部分传递的redux函数获得此响应。我想链接一个。然后在调用我的函数后立即阻塞 我尝试创建一个承诺并在操作中返回该承诺,但在链接.then/.catch时,它会自动解决一个错误 我也尝试过这样做,但没有做出承诺 以下是我的行动: export const fetchHomewor

我正在使用react native和redux创建一个应用程序。我的应用程序应该向firebase rest api发送请求,以获取用户的todo。在我的react本机应用程序中,我通过react本机组件的connect部分传递的redux函数获得此响应。我想链接一个。然后在调用我的函数后立即阻塞

我尝试创建一个承诺并在操作中返回该承诺,但在链接.then/.catch时,它会自动解决一个错误 我也尝试过这样做,但没有做出承诺

以下是我的行动:

export const fetchHomework = () => {
  return (dispatch, getState) => {
      dispatch(uiStartLoading());
      dispatch(uiStartFetchingHomework());
      dispatch(authGetToken())
      .catch(err => {
        dispatch(errHandler(err))
      })
      .then(token => {
        const uid = getState().userid;

        fetch(restAPI)
        .catch(err => {
          dispatch(errHandler(err));
        })
        .then(res => res.json())
        .then(response => {
          dispatch({
            type : 'SET_HOMEWORK_FOR_AGENDA',
            homework : response
          })
          dispatch(uiStopLoading());
          dispatch(uiStopFetchingHomework());
        })
        .catch(err => {
          dispatch(errHandler(err));
          dispatch(uiStopLoading());
          dispatch(uiStopFetchingHomework());
        })

      })
      dispatch(uiStopLoading());
      dispatch(uiStopFetchingHomework());
  }
}
注意:RESTAPI将替换为RESTAPI的url 这里是我获取这些数据的地方:

this.setState({refreshing: true});
this.props.retrieveHomework();
this.setState({refreshing: false, firebaseItems : this.props.homework});
this.loadItems(this.state.selectedDay);

(刷新时在函数中调用)

我希望当我在RetrieveHomeship之后链接一个.then块时,then块会等待函数完成,然后运行其中的代码,但事实并非如此。发生的情况是,它要么跳过then块,要么抛出catch块捕获的错误

编辑:
this.props.retrieveHome作业是一个指向异步操作的函数,因为我正在使用redux thunk。

您需要将所有要等待的代码移动到
中。然后

this.props.retrieveHomework()
  .then(() => {
    this.setState({refreshing: false, firebaseItems : this.props.homework});
    this.loadItems(this.state.selectedDay); // If this is async, you need to `return` it here as well
  });

我是否正确
props.RetrieveHomeship
指的是
FetchHomeship
异步操作调度程序?使用了
redux thunk
吗?@skyboyer是的,你是对的。我会在我的问题中加上这一点来澄清嘿,马特。这确实起到了作用,但也带来了另一个问题。由于我使用的是异步的redux thunk,所以我的操作调用了一个同步函数来设置数据的状态,并且异步函数在同步函数完成之前返回。这意味着当我调用时,我没有得到更新的状态,因为设置它的sync函数尚未完成。在返回异步函数/调用之前,如何确保同步函数返回。那么,问题是,
React.Component#setState
也是异步的。这就是为什么建议使用函数作为第一个参数调用它,比如
This.setState(prevState=>newState)
,顺便说一句,它应该可以解决执行顺序的问题。@rml我确实理解这一点,但我认为我的问题令人困惑,因为我没有提供代码。我的意思是,我调用一个reducer来设置我在异步调度中的状态,而reducer在异步调用完成之前没有完成,因此它不会及时更新状态。如何使异步函数在设置状态之前不会返回?如果它很容易出现争用情况,我可能会开始重新思考整个状态管理。我认为@rml的建议是:
this.setState({刷新:false,firebaseItems:this.props.homography},()=>this.loadItems(this.state.selectedDay))
虽然
setState
确实将回调函数或对象作为其第一个参数,但如果在新状态值中引用了
this.state
,则只需使用回调
setState
还接受第二个参数,这是在
setState
完成后运行的函数,因为@rml指出,
setState
本身是异步的