如何在React中使用Redux Saga进行等待?

时间:2019-05-12 14:29:17

标签: reactjs redux-saga

await似乎不适用于Redux传奇。我需要等待API调用完成,然后执行其余代码。现在发生的是,AFTER CALLRESPONSE之前被打印,这意味着等待似乎根本不起作用。我正在使用异步调用,但不确定从redux saga方面需要额外做些什么?

async componentWillMount() {
    console.log("BEFORE CALL")
    await this.props.getUserCredit()
    console.log("AFTER CALL")

}

mapDispatchToProps = (dispatch) => {
  return {
    getUserCredit: () => dispatch(getUserCredit()),
  }
};

connect(null, mapDispatchToProps)(MyComponent);

Action

export const getUserCredit = () => {
  return {
    type: GET_USER_CREDIT,
  };
};

Redux Saga

const getUserCreditRequest = async () => {
  const response = await Api.get(getCreditUrl)
  console.log("REPONSE!!!")
  console.log(response)
  return response
}

function* getUserCredits() {
  try {
    const response = yield call(getUserCreditRequest);
    if (response.status === okStatus) {
      yield put({
        userCredit: response.data.userCredit
      }
      ));
    }
  } catch (error) {}
}

export function* getUserCredit() {
  yield takeLatest(GET_USER_CREDIT, getUserCredits);
}

export default function* rootSaga() {
  yield all([fork(getUserCredit)]);
}

2 个答案:

答案 0 :(得分:1)

通常,初始化/获取发生在componentDidMount期间,并且在组件内部不使用asyncawait。让传奇的中间件通过yield来完成任务。

// In your component
componentDidMount() { // not async
  this.props.getUserCredit(); // dispatch `GET_USER_CREDIT` action 
}

mapDispatchToProps = (dispatch) => {
  return {
    getUserCredit: () => dispatch(getUserCredit()),
  }
};

connect(null, mapDispatchToProps)(YourComponent);

答案 1 :(得分:0)

您不应该使用async / await模式。 redux-saga通过yield关键字进行处理。到call解决时,您将在response中获得可用的值。

actions.js中,您应该执行一个将数据携带到减速器的操作:

export function getUserCredits(userCredit) {
  return {
    type: types.GET_USER_CREDIT_SUCCESS,
    payload: userCredit
  };
}

您的传奇应该像这样处理API调用:

function* getUserCredits() {
  try {
    const response = yield axios.get(getCreditUrl); <--- This should work
    // No need for if here, the saga will catch an error if the previous call failed
    yield put(actions.getUserCredits(response.data.userCredit));
  } catch (error) {
    console.log(error);
  }
}

编辑example结合使用带有redux-saga的axios