【问题标题】:useEffect is not triggered on redux store get updated在 redux 商店更新时不会触发 useEffect
【发布时间】:2021-05-05 09:48:49
【问题描述】:
export default function Cart(props) {
  const dispatch = useDispatch();
  
  const branch = useSelector((state) => get(state, "vendor.currentBranch"));
const orderInput = useSelector((state) => get(state, "order.orderInputs"));

  const [orderResult, setOrderResult] = useState(null);
  let orderItemLength = orderInput.length

  useEffect(() => {
    let payload = {
      branch_uuid: get(branch, "uuid"),
      menu_items: orderInput,
    };
    
    dispatch(calculateOrder(payload))
      .then((result) => {
        setOrderResult(result);
      })
      .catch(() => {});
   
  }, [orderInput]);

  const deleteItem = (index) => {
    remove(orderInput, (oi, i) => index === i);
    dispatch({
      type: ADD_ORDER_INPUT,
      payload: orderInput,
    });
  };

  return (
          <div className={styles.cartbody} id="scrollstyle-4">
            {map(get(orderResult, "orderItems", []), (oi, i) => {
              return (
                <div className={styles.cartProductBox}>
                  <div className={styles.productName}>
                    <p className={styles.textRed}>
                      <span className={styles.qunatity}>
                        {get(oi, "quantity")}
                      </span>
                      {get(oi, "item_name")}
                      <Popconfirm
                        placement="rightBottom"
                        title={"Are you sure you want to remove this item?"}
                        onConfirm={() => {
                          deleteItem(orderInput,i);
                        }}
                        okText="Yes"
                        cancelText="No"
                      >
                        <DeleteOutlined />
                      </Popconfirm>
                    </p>
                    <span className={styles.subItem}>
                      {map(get(oi, "orderItemAddons", []), (oia, i) => {
                        return `${i === 0 ? "" : ","} ${get(
                          oia,
                          "addon_type_name"
                        )} `;
                      })}
                    </span>
                  </div>

                  <div>
                    <div>
                      <span className={styles.qunatity}>
                        $ {round(get(oi, "item_amount"), 2)}
                      </span>
                    </div>
                    <div style={{ marginTop: 10 }}>
                      {get(oi, "orderItemAddons", []).length > 0 && (
                        <span className={styles.addonPrice}>
                          $ {round(get(oi, "addon_amount"), 2)}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
  );
}

这是我的减速器代码

import {
  ADD_SERVICE,
  ADD_ORDER_INPUT,
  ADD_CALCULATED_ORDER,
} from "../../constants/ActionTypes";

const orderReducer = (
  state = { serviceType: null, orderInputs: [] },
  action
) => {
  switch (action.type) {
    case ADD_SERVICE:
      return { ...state, serviceType: action.payload };

    case ADD_ORDER_INPUT:
      return { ...state, orderInputs: action.payload };

    case ADD_CALCULATED_ORDER:
      return { ...state, orderInputs: action.payload };

    default:
      return { ...state };
  }
};

export default orderReducer;

在上面的代码中,当我从另一个组件添加订单项时,useEffect 被触发,但是当我删除 orderItem(如您在 deleteItem() 函数中看到的那样)时,我的 redux 商店没有触发 useEffect,我的 useEffect触发器依赖是OrderInput 变量,如代码所示。 我还尝试将 useEffect 的依赖项设置为顺序数组的长度 OrderInput

请帮助我知道我做错了什么?

【问题讨论】:

  • 这里使用了什么删除:remove(orderInput, (oi, i) =&gt; index === i); 以及 ADD_ORDER_INPUT 的减速器是什么?
  • 在商店中查看减速器的代码会很有用。最可能的原因是您没有一成不变地更新商店。
  • @HMR remove 是 lodash 中的一个函数,它从指定索引的订单输入数组中删除项目,我更新了上面的订单缩减器代码。另外,我在另一个组件中使用了相同的减速器并且工作正常,并且我在这个组件中的 useEffect 被完美地调用
  • @Chris 谢谢我在替换 ``` const newOrderInput= [...orderInput]; 后忘记了这个概念调度({类型:ADD_ORDER_INPUT,有效载荷:newOrderInput,}); ```它开始工作了

标签: reactjs react-redux react-hooks use-effect react-lifecycle-hooks


【解决方案1】:

由于 Chris Answer,遇到了同样的问题并得到了解决。

提供一些详细说明,希望它可以帮助下一个人:

最初没有工作,当 redux 存储更改时,useEffect 没有触发。

  // Redux: Subscribe to user Store
  const userStateRedux = useSelector((state: RootState) =>state.user);

  useEffect(() => {
      console.log('hello',userStateRedux);
  }, [userStateRedux]);

Redux 需要引用另一个对象来检测更改状态 (在你的 reducer 中执行不可变更新)

In your reducer.js

//Mutable Update: Still referencing ur initial State
state.user=action.user;
state.token=action.token;

//Immutable Update: Referencing a new Object <- USE THIS
state={
      user:action.user,
      token:action.token
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2023-01-26
    • 2020-02-06
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多