Javascript 反应本机useState函数参数混乱
我正在编写一个React本地教程。在下面的代码中,courseGoals是使用useState函数在状态中声明的,但是在调用addGoalHandler函数中的setCourseGoals函数时,currentGoals已作为参数传递,而不是courseGoals。为什么会这样?这是因为如果我们使用的是设置courseGoals中的函数,参数将始终自动获取courseGoals值吗Javascript 反应本机useState函数参数混乱,javascript,reactjs,react-native,use-state,Javascript,Reactjs,React Native,Use State,我正在编写一个React本地教程。在下面的代码中,courseGoals是使用useState函数在状态中声明的,但是在调用addGoalHandler函数中的setCourseGoals函数时,currentGoals已作为参数传递,而不是courseGoals。为什么会这样?这是因为如果我们使用的是设置courseGoals中的函数,参数将始终自动获取courseGoals值吗 export default function App() { const [enteredGoal, set
export default function App() {
const [enteredGoal, setEnteredGoal] = useState('');
const [courseGoals, setCourseGoals] = useState([]);
const goalInputHandler = (enteredText) => {
setEnteredGoal(enteredText);
};
const addGoalHandler = () => {
setCourseGoals(currentGoals => [...currentGoals, enteredGoal]);
};
对
代码中的[…currentGoals,enteredGoal]
将在课程目标
数组中添加新目标
可以根据需要重命名参数。而且它仍然有效。例如:
setCourseGoals(courceGoals => [...courceGoals, enteredGoal]);