我正在使用 React Native + Redux + Redux-thunk 我对 redux 和 React Native 没有太多经验
我正在组件内调用一个操作。
this.props.checkClient(cliente);
if(this.props.clienteIsValid){
...
}
在该操作中,有一个对 api 的调用需要几秒钟的时间。
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 响应来了解客户端是否有效。也就是说,我需要解决该操作,然后验证客户端是否有效。
最佳答案
您可以从操作中返回一个 promise ,以便调用变得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 wait 而不是 then
来处理您的 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) {
...
}
}
这做同样的事情。
关于reactjs - Redux - 如何调用一个 Action 并等待它被解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54054887/