我正在为这个应用程序使用react redux、redux工具包、stripe。付款成功后,我想保存用户的订单,并将他们重定向回主页。不幸的是,有一行代码没有执行:
const handleFormSubmit = async (e) => {
e.preventDefault();
setProcessing(true);
const payload = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement)
}
});
if (payload.error) {
setError(`Payment failed ${payload.error.message}`);
setProcessing(false);
} else {
setError(null);
setProcessing(false);
setSucceeded(true);
dispatch(postOrderToDatabase); <--- This code seems like never run
alert('Your payment is success, you will be redirected to the homepage');
history.replace('/');
};
}
我认为该行动没有发出,在redux扩展的行动部分找不到。
我认为可能出了问题的是,我在一个文件中有2个createAsyncThunk,我认为这就是为什么代码被忽略的原因。
const initialState = {
name: "",
email: "",
address: "",
contact: "",
postalCode: "",
items: [],
totalAmount: "",
}
export const getCartItem = createAsyncThunk(
'order/getCartItem',
async (dispatch, {getState}) => {
const orderedItem = getState().cartItem.cartItem
return orderedItem;
}
);
export const postOrderToDatabase = createAsyncThunk(
'order/postOrder',
async (dispatch, {getState}) => {
const orderDetails = getState().order;
fetch('orders', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: orderDetails.name,
contact: orderDetails.contact,
email: orderDetails.email,
address: orderDetails.address,
postalCode: orderDetails.postalCode,
orderedItems: orderDetails.items,
totalAmount: orderDetails.totalAmount,
})
})
}
)
const OrderDetailsSlice = createSlice({
name: "orderDetails",
initialState,
reducers: {
setOrderDetails: (state, action) => {
state.name = action.payload.name
state.email = action.payload.email
state.address = action.payload.address
state.contact = action.payload.contactNumber
state.postalCode = action.payload.postalCode
}
},
extraReducers: {
[getCartItem.fulfilled]: (state, action) => {
state.items = action.payload
let num = action.payload.reduce((a, c) => a + (c.cartItem.price*c.unit), 0)
state.totalAmount = Number(num.toFixed(2))
},
[postOrderToDatabase.fulfilled]: (state, action) => {
state.name = "";
state.email = "";
state.address = "";
state.contact = "";
state.postalCode = "";
state.items = [];
state.totalAmount = "";
}
}
});
知道为什么这不起作用吗?
您需要在调度asyncThunk之前调用它。
所以,
dispatch(postOrderToDatabase());
不是
dispatch(postOrderToDatabase);