简体   繁体   English

reactjs中状态数组的正确更新

[英]correct update of state array in reactjs

i tried to build a TODO app with React Native我试图用 React Native 构建一个 TODO 应用程序

const [ enteredGoal, setEnteredGoal ] = useState("");
const [ courseGoals, setCourseGoals ] = useState([]);

const goalInputHandler = (enteredText) => {
  setEnteredGoal(enteredText);
};


const addGoalHandler = () => {
  let arrGoals = courseGoals;
  arrGoals.push(enteredGoal);
  setCourseGoals(arrGoals);
};

return (
    <View style={styles.screen}>
      <View style={styles.inputContainer}>
        <TextInput style={styles.input} onChangeText={goalInputHandler}/>
        <Button title="ADD" onPress={addGoalHandler}/>
      </View>
      <View>
        { 
          courseGoals.map((goal) => {
            <View key={goal} style={styles.listItem}><Text>{goal}</Text></View>
          })
        }
      </View>
    </View>
  );

the idea is to list the setCourseGoals array, but apparently after assigning a new text, it doesn't list anything.这个想法是列出 setCourseGoals 数组,但显然在分配新文本后,它没有列出任何内容。 Its not until the text changes that the list is re-rendered.直到文本更改时,才会重新呈现列表。 Any idea on why this happens??关于为什么会发生这种情况的任何想法? the "useState" function is asynchronous, which assigns the value after rendering? “useState”函数是异步的,渲染后赋值? Thanks in advance.提前致谢。

The problem is coming from addGoalHandler问题来自addGoalHandler

const addGoalHandler = () => {
  let arrGoals = courseGoals;
  arrGoals.push(enteredGoal);
  setCourseGoals(arrGoals);
};

What happened was you are using push method to push it to courseGoals which was mutated the state, one of the option you can do is update to below发生的事情是您使用push方法将其推送到状态发生变化的courseGoals ,您可以执行的选项之一是更新到下面

const addGoalHandler = () => {
  let arrGoals = [...courseGoals, enteredGoal];
  setCourseGoals(arrGoals);
};

The idea is that, using spread syntax allowing you to create a new copy of array instead of mutated the previous state, and of course it can be shorten down to single line as below这个想法是,使用扩展语法允许您创建数组的新副本而不是改变以前的状态,当然它可以缩短为单行,如下所示

const addGoalHandler = () => setCourseGoals([...courseGoals,enteredGoal])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM