简体   繁体   English

React 钩子不更新组件

[英]React hooks not updating components

I'm trying to set up an order list with react hooks.我正在尝试使用反应挂钩设置订单列表。 The method is correct but the components aren't updating until i force it from React dev tools.该方法是正确的,但组件不会更新,直到我从 React 开发工具强制它。 The button that add the order is in a component and the list is a different component.添加订单的按钮在一个组件中,而列表是一个不同的组件。

I tried setting useEffect but the result is the same.我尝试设置 useEffect 但结果是一样的。

Here is the state declaration and the method这是状态声明和方法

const [orderList, setOrderList] = React.useState([]);

const addToOrderList = (order) => {
    const list = orderList;
    if (list)
      list.push(order);
    setOrderList(list);
  }

And here the components in the render这里是渲染中的组件

<div className="w-3/5">
  <ItemDeliveryCard
    fromMenu={true}
    selectedMenu={selectedMenu}
    orderList={orderList}
    onClickHandler={(order) => addToOrderList(order)}
  />
</div>
<div >
  <DeliveryCard orderListProp={orderList} />
</div>

The button in ItemDeliveryCard ItemDeliveryCard的按钮

<button
   onClick={() => onClickHandler(product)}
   className={gradients.redGradToL + " w-80 flex flex-row items-center justify-center mb-5"}
>
   <p className="uppercase">select this offer</p>
</button>

I tried the solutions from this post but useEffect doesn't seems to work我尝试了这篇文章中的解决方案,但 useEffect 似乎不起作用

You are mutating state where you need to treat it as immutable , try instead:您正在改变状态,您需要将其视为不可变的,请尝试:

const addToOrderList = (order) => {
  if (orderList) {
    setOrderList(prevList => [...prevList, order]);
  }
}

The React hook way to modify a state:修改状态的 React 钩子方式:

const addToOrderList = (order) => {
  setOrderList(list => (list ? list : []).concat(order));
}

A little explanation:一点解释:

  1. Reason your code doesn't trigger update, is because the new value of list that you set, setOrderList(newValue) , is the same array reference as old value, React doesn't detect this mutation, thus no update.您的代码不会触发更新的原因是因为您设置的列表的新值setOrderList(newValue)与旧值是相同的数组引用,React 没有检测到这种变化,因此没有更新。
  2. It's recommended you use the updater function pattern:建议您使用更新程序功能模式:
setValue(oldValue => {
  /* whatever mutation logic you need */
  return newValue
})

Instead of moving the mutation logic outside then set the final value, like what you do currently.而不是将变异逻辑移到外面然后设置最终值,就像你目前所做的那样。 Reason is that this pattern would mitigate the stale closure problem .原因是这种模式将减轻陈旧的关闭问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM