分派完成后如何从 useSelector 获取状态?

时间:2021-05-11 14:36:03

标签: reactjs redux react-redux

我有一个 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)}
  })}
);

2 个答案:

答案 0 :(得分:1)

这就是 img = -laplace(img,5); % LoG with sigma=5 img = img > 0.05; % 0.05 is just above 0 img = areaopening(img,1000); % remove objects smaller than 1000 pixels 的用途:

useEffect()

答案 1 :(得分:1)

根据定义,函数组件主体中定义的回调只能访问在创建回调时渲染组件时存在的状态、道具和值。

如果您正在调度一个操作,那么该代码不可能访问下一行的 Redux 状态(甚至是 React 状态)。

如果您确实需要立即访问新的 Redux 状态,可以通过 thunk 来实现,该 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));
}