向数组 React 添加新元素时的无限循环



问题如下:

当我收到parent componentprops时,datanew element,必须添加新卡,但取而代之的是代码开始添加这张卡infinite number of times

如何解决这个问题?代码如下

const fetchCards = () => {
return Axios(apiOptions('GET')).then(
response => response.data,
error => {
console.log(`[Error]: ${error}`);
}
);
};
const addCard = props => {
return Axios(apiOptions('POST', props))
.then(result => result.data)
.catch(error => console.log(error));
};
const PlacesList = props => {
const [cards, setCards] = useState([]);
useEffect(() => {
fetchCards().then(res => setCards(res))
}, []);
// Problem with this part 
if (props.newCard.titleValue !== undefined) {
console.log(props.newCard.titleValue);
addCard(props.newCard).then(res => setCards(cards.concat(res)));
}

const createCards = () => {
return cards
.map((card, id) => {
if (id > cards.length - 10) {
return (
<PlaceCard
title={card.name}
url={card.link}
/>
);
}
return false;
})
.reverse();
};
return <div className="places-list root__section">{createCards()}</div>;
};
export default PlacesList;

简化示例代码沙盒

注意:下面的答案基于您给出的代码沙箱,而不是您提供的片段:

要回答导致问题的原因:

if (props.newItem) {
setItems(items.concat([10]));
}

此代码块呈现在组件根目录上,而不是在任何useEffect或回调函数内部呈现。组件的每个"渲染"都将调用setItems并且由于任何状态更改(这些更改由setStateuseState的第二个结果触发(都会导致组件上的重新渲染,因此将发生的情况是它将无限地重新渲染。


要回答您的问题,请执行以下操作:

在列表组件上,添加以下内容:


useEffect(() => {
if (props.newItem) {
setItems(items.concat([10]));
}
}, [props.newItem]);`

仅当props.newItem的值已更新时,此操作才会生效。

但是当您再次单击该按钮时,这将不起作用,因为newItems的值始终是true.

要解决此问题,请在调用 List 时添加 setNewItem (即(:

<List newItem={newItem} setNewItem={setNewItem} />

这将通过为您的 List 组件提供更改项目值的能力。 因此,让我们将其添加到上面的第二个代码块上的useEffect中,如下所示:

useEffect(() => {
if (props.newItem) {
setItems(items.concat([10]));
props.setNewItem(false);
}
}, [props.newItem]);`

我们将其设置为 false,以便它始终切换newItem的值,并始终在您的列表中添加新项目。

最新更新