react.js错误**无法在现有状态转换期间更新**



谁能告诉我为什么当用户没有shippingAddress数据时重定向用户时会出现此错误?我敢肯定问题是与props.history.push. 当我把它注释掉时,没有错误发生。

const PaymentMethodScreen = (props) => {
const [paymentMethod, setPaymentMethod] = useState("PayPal");
const dispatch = useDispatch();
const cart = useSelector(state => state.cartReducer);
const { shippingAddress } = cart;
if(!!shippingAddress){
props.history.push('/shipping')
};
const submitHandler = (e) => {
e.preventDefault();
dispatch({
type: actions.CART_SAVE_PAYMENT_METHOD,
payload: paymentMethod,
});
props.history.push("/placeholder");
};
return (
<div>
<CheckoutSteps step1 step2 step3 />
<form className="form" onSubmit={submitHandler}>
// *not useful*
</div>
<div>
<button className="primary" type="submit">
Continue
</button>
</div>
</form>
</div>
)
};
export default PaymentMethodScreen;

在调度尚未完成更新存储时意外导航到另一个页面

要解决这个问题,等待调度完成后再导航:

const submitHandler = async (e) => {
e.preventDefault();
await dispatch({
type: actions.CART_SAVE_PAYMENT_METHOD,
payload: paymentMethod,
});
props.history.push("/placeholder");
};

最新更新