英文:
React infinite rendering: a choice between mutating state array or not
问题
作为标题。根据https://stackoverflow.com/questions/76246183/cannot-see-updates-from-child-component-through-parents-callback-case-array-an/76246219#76246219中的建议,我不应该像这样突变状态。
所以,在https://codepen.io/jadecubes/pen/dygjGZL中,我尝试setWords(一个新数组),但它触发了无限渲染。
此外,要删除数组中的所有项,建议的方法是什么?来自https://stackoverflow.com/questions/72478888/remove-all-the-elements-of-the-array-in-react-js,也许直接突变不是一个好主意?欢迎任何建议。
英文:
As title. I shouldn't mutate state like this based on suggestion in https://stackoverflow.com/questions/76246183/cannot-see-updates-from-child-component-through-parents-callback-case-array-an/76246219#76246219
So, in https://codepen.io/jadecubes/pen/dygjGZL, I try to setWords(a new array), but it triggers infinite rendering.
// React.js libraries are added as external scripts in the JS settings of this pen
const { useState, useEffect } = React;
A = () => {
const [info, setInfo] = useState("Hello world.");
const [entered, setEntered] = useState('');
return (
<>
<input type="text"
onChange={(e)=>{setInfo(e.target.value);}}
onKeyUp={(e)=>{if(e.key=='Enter') setEntered(info); }}
/>
<B enteredTxt={entered}/>
<h1>{info}</h1>
</>
);
};
B = (props) => {
const [words,setWords] = useState([]);
words.length=0;//I should not do this. I should re-assign a new array like setWords()
words.push(props.enteredTxt);
setWords(arrayGen());//But when I do this, the react infinite rendering happens!
return(
<div>
{words}
</div>
);
}
const arrayGen=()=>{
return ['This ','is ','hello ', 'world!'];
}
const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<A />);
Also, what's the suggested way to remove all items in an array? From https://stackoverflow.com/questions/72478888/remove-all-the-elements-of-the-array-in-react-js , Maybe direct mutating is not a good idea? Any advice is welcome.
newArray = this.state.data.slice();
答案1
得分: 0
如果您只想在 enteredTxt
改变时调用 setWords
,您应该像这样使用 useEffect:
useEffect(() => {
setWords(arrayGen());
}, [props.enteredTxt]);
要移除所有项目,您可以简单地赋一个新数组:
`newArray = [];`
<details>
<summary>英文:</summary>
If you only want to call `setWords` only when `enteredTxt` changes, you should use useEffect like this:
useEffect(() => {
setWords(arrayGen());
}, [props.enteredTxt])
To remove all items you can simply assign a new array:
`newArray = [];`
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论