【发布时间】: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;
【问题讨论】: