Redux - 如何调用一个动作并等待它被解决 [英] Redux - how to call an action and wait until it is resolved
问题描述
我正在使用 react native + redux + redux-thunk我对 redux 和 react native 没有太多经验
I'm using react native + redux + redux-thunk I do not have much experience with redux and react native
我正在我的组件内调用一个动作.
I'm calling an action inside my component.
this.props.checkClient(cliente);
if(this.props.clienteIsValid){
...
}
在该操作中,会调用一个需要几秒钟的 API.
and within that action there is a call to an api that takes a few seconds.
export const checkClient = (cliente) => {
return dispatch => {
axios.get(`${API_HOST}/api/checkclient`, header).then(response => {
dispatch({type: CHECK_CLIENT, payload: response.data }); //valid or invalid
}).catch((error) => { });
}
}
我的问题是如何延迟动作的返回直到api响应完成?我需要 api 响应才能知道客户端是有效还是无效.也就是说,我需要解析动作,然后验证客户端是有效还是无效.
My question is how can I delay the return of the action until the api response is completed? I need the api response to know if the client is valid or invalid. That is, I need the action to be resolved and then verify that the client is valid or invalid.
推荐答案
你可以从 action 中返回一个 promise,这样调用就变成 thenable:
You can return a promise from the action, so that the call becomes thenable:
// Action
export const checkClient = (cliente) => {
return dispatch => {
// Return the promise
return axios.get(...).then(res => {
...
// Return something
return true;
}).catch((error) => { });
}
}
class MyComponent extends React.Component {
// Example
componentDidMount() {
this.props.checkClient(cliente)
.then(result => {
// The checkClient call is now done!
console.log(`success: ${result}`);
// Do something
})
}
}
// Connect and bind the action creators
export default connect(null, { checkClient })(MyComponent);
这可能超出了问题的范围,但如果您愿意,您可以使用 async await 而不是 then
来处理您的承诺:
This might be out of scope of the question, but if you like you can use async await instead of then
to handle your promise:
async componentDidMount() {
try {
const result = await this.props.checkClient(cliente);
// The checkClient call is now done!
console.log(`success: ${result}`)
// Do something
} catch (err) {
...
}
}
这做同样的事情.
这篇关于Redux - 如何调用一个动作并等待它被解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!