【问题标题】:Component not re-rendering when updating state within map function在地图功能中更新状态时组件不重新渲染
【发布时间】:2022-02-14 23:10:35
【问题描述】:

我不知道为什么当我单击运行函数update 的按钮时组件没有自动重新渲染。我看到单击按钮后,状态会更新,但列表不会自动重新呈现。调用setFoobar 时组件不应该重新渲染吗?

import React, { useEffect, useState } from "react";

const SomeList = () => {
  const [foobar, setFoobar] = useState([
    {
      description: "description1",
      date: "date1",
    },
    {
      description: "description2",
      date: "date2",
    },
  ]);
  const update = () => {
    const newFoobar = foobar;
    newFoobar.push({
      description: "This new item should render in view",
      date: "asdf",
    });
    setFoobar(newFoobar);
  };
  const generateList = foobar((each, idx) => {
    return (
      <div key={idx}>
        <div>{each.description}</div>
        <div>{each.date}</div>
        <div>
          <button onClick={update}>Click</button>
        </div>
      </div>
    );
  });
  return <div>{generateList}</div>;
};

export default SomeList;

【问题讨论】:

    标签: reactjs next.js use-state


    【解决方案1】:

    您的代码不起作用,因为const newFoobar = foobar;,先前的状态和新的状态是同一个对象,因此组件不会重新渲染。所以你必须创建一个新对象并更新它

    const update = () => {
        const newFoobar = [...foobar];
        newFoobar.push({
          description: "This new item should render in view",
          date: "asdf",
        });
        setFoobar(footer);
      };
    

    【讨论】:

    • 糟糕,我在写这篇文章时打错了。我修正了错字。我的问题是状态得到更新,但它不会使用新的状态值渲染组件,直到另一个 setState 在其他地方触发。我试图弄清楚为什么这个逻辑不会自动触发重新渲染。
    • 实际上,它正在工作,事实证明传播语法对于重新渲染是必要的。谢谢!
    猜你喜欢
    • 2021-10-15
    • 2018-06-05
    • 2023-03-09
    • 2019-07-28
    • 2023-03-20
    • 1970-01-01
    • 2021-03-15
    • 2021-07-25
    • 2020-10-24
    相关资源
    最近更新 更多