reactjs React无限渲染:在是否改变状态数组之间进行选择

5kgi1eie  于 2023-05-17  发布在  React
关注(0)|答案(1)|浏览(151)

作为标题。我不应该根据Cannot see updates from child component through parent's callback(case array and push)中的建议这样改变状态
因此,在https://codepen.io/jadecubes/pen/dygjGZL中,我尝试setWords(一个新数组),但它会触发无限渲染。

// 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 />);

另外,删除数组中所有元素的建议方法是什么?从Remove all the elements of the array in React JS,也许直接突变不是一个好主意?任何建议都欢迎。

newArray = this.state.data.slice();
7tofc5zh

7tofc5zh1#

如果你只想在enteredTxt发生变化时调用setWords,你应该像这样使用useEffect:

useEffect(() => {
  setWords(arrayGen());
}, [props.enteredTxt])

要删除所有项目,您可以简单地分配一个新数组:
newArray = [];

相关问题