我有一个FormCheck组件,它在onChange事件上调用handleChange函数。任务:更改复选框的状态,并使用新状态向服务器发送请求。问题是提交是稍后完成的,即在提交之前执行getSelectedCategories函数。
const data = useSelector((state) => state.products);
const boxes = getBoxes(data);
const handleChange = (id) => {
dispatch(setFilterCategory(id));
const selectedCategories = getSelectedCategories(data);
console.log(selectedCategories); // This is done before the dispatch while the state changes
dispatch(fetchProducts(selectedCategories);
};
return (
{boxes.map(item => {
return <FormCheck label={item.value} checked={item.isChecked} onChange={() => handleChange(item.id)}
})}
);
根据定义,在函数组件主体中定义的回调只能访问在组件呈现时创建回调时存在的状态、道具和值。
如果您正在调度一个操作,则该代码不可能访问下一行的新Redux状态(甚至React状态(。
如果你确实需要立即访问新的Redux状态,你可以通过thunk来完成,它可以访问getState
:
const updateCategoryAndFetch = (category) => {
return (dispatch, getState) => {
dispatch(setFilterCategory(id));
const selectedCategories = getSelectedCategories(getState());
dispatch(fetchProducts(selectedCategories)
}
}
// later, in the component:
const handleChange = (id) => {
dispatch(updateCategoryAndFetch(id));
}
这就是useEffect()
的用途:
const data = useSelector((state) => state.products);
const selectedCategories = getSelectedCategories(data);
const handleChange = (id) => {
dispatch(setFilterCategory(id));
};
// is executed whenever selectedCategories changes
useEffect(() => {
dispatch(fetchProducts(selectedCategories);
}, [selectedCategories])