我在React Native应用程序中具有功能组件,并且正在调度HTTP调用。如果发生某些错误,我将其存储在redux中,问题是当我访问错误值时,我得到了空值
function IncomingOrder(props) {
function acceptOrder(orderId, coords) { // I call this from a button
const response = await actions
.accept(token, orderId, coords) //this is the async function
.catch((e) => {
showError(props.error);
});
}
...
}
...
function mapStateToProps(state) {
return {
token: state.auth.token,
error: state.deliveries.error
};
}
function mapDispatchToProps(dispatch) {
return {
actions: {
accept: (token, id, coords) => {
return dispatch(Order.accept(token, id, coords));
}
}
};
}
答案 0 :(得分:0)
该问题很可能是由acceptOrder()
异步操作创建者引起的。
Redux dispatch
将在您的诺言得到解决/拒绝后立即更新。因此,当您的错误处理程序(Promise.prototype.catch or catch(){}
)启动时,无法保证已分派操作或更新状态树。
您要做的是在异步操作创建者上使用此逻辑
// action module Order.js
export const accept = (token, id, coords) => dispatch => {
fetch('/my/api/endpoint')
.then(response => doSomethingWith(response))
.catch(err => dispatch(loadingFailed(err)); // <----- THIS is the important line
}
// reducer.js
// you want your reducer here to handle the action created by loadingFailed action creator. THEN you want to put the error in the state.
// IncomingOrder.js
function IncomingOrder(props) {
function acceptOrder(orderId, coords) { // I call this from a button
actions.accept(token, orderId, coords);
// You don't need to wait for this, as you're not gonna work with the result of this call. Instead, the result of this call is put on the state by your reducer.
}
render() {
const { error } => this.props; // you take the error from the state, which was put in here by loadingFailed()
if (error) {
// render your error UI
} else {
// render your regular UI
}
}
}
function mapStateToProps(state) {
return {
token: state.auth.token,
error: state.deliveries.error // <--- I suppose your error is already here (?)
};
}