【问题标题】:React Native useState function parameter confusionReact Native useState 函数参数混淆
【发布时间】:2021-06-23 23:26:28
【问题描述】:

我正在编写 React Native 教程。在下面的代码中,courseGoals 是使用 useState 函数在状态中声明的,但是当在 addGoalHandler 函数中调用 setCourseGoals 函数时,currentGoals 已作为参数传递,而不是 courseGoals。为什么是这样?是不是因为如果我们在 setCourseGoals 中使用一个函数,参数会自动总是得到 courseGoals 的值?

export default function App() {
  const [enteredGoal, setEnteredGoal] = useState('');
  const [courseGoals, setCourseGoals] = useState([]);

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

  const addGoalHandler = () => {
    setCourseGoals(currentGoals => [...currentGoals, enteredGoal]);
  };

【问题讨论】:

    标签: javascript reactjs react-native use-state


    【解决方案1】:

    是的。

    代码中的[...currentGoals, enteredGoal] 是在courseGoals 数组中附加新目标。

    您可以根据需要重命名参数。它仍然可以工作。例如:

    setCourseGoals(courceGoals => [...courceGoals, enteredGoal]);
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2019-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 2016-02-14
      相关资源
      最近更新 更多