await
似乎不适用于Redux传奇。我需要等待API调用完成,然后执行其余代码。现在发生的是,AFTER CALL
在RESPONSE
之前被打印,这意味着等待似乎根本不起作用。我正在使用异步调用,但不确定从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)]);
}
答案 0 :(得分:1)
通常,初始化/获取发生在componentDidMount
期间,并且在组件内部不使用async
或await
。让传奇的中间件通过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