React无限渲染:在修改状态数组或不修改之间进行选择

huangapple go评论48阅读模式
英文:

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(() =&gt; {
      setWords(arrayGen());
    }, [props.enteredTxt])

To remove all items you can simply assign a new array:

`newArray = [];`

</details>



huangapple
  • 本文由 发表于 2023年5月14日 16:12:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定