setState中的神秘参数,为什么会起作用?

完成 TypeScript + React 课程并构建待办事项列表。不过,我的问题是关于反应功能。


在添加 Todo 的处理程序中,在 setState 中声明了这个函数


const App: React.FC= () => {


  const [todos, setTodos] = useState<Todo[]>([])


  const todoAddHandler = (text: string) => {

    // when its called.... where does the prevTodos state come from?

    setTodos(prevTodos => [...prevTodos, 

      {id: Math.random().toString(), text: text}])

  }


  return (

    <div className="App">

      <NewTodo onAddTodo={todoAddHandler}/>

      <TodoList items={todos}></TodoList>

    </div>

  );

}


export default App;

当在setState中调用该函数时,它会自动调用当前状态。这只是 setState 的一个特性吗?如果你在其中声明一个函数,参数将始终是函数被调用时的当前状态?


当这个参数刚刚...工作时非常困惑。:#


慕运维8079593
浏览 78回答 2
2回答

慕标琳琳

这只是 setState 的一个特性吗?- 是的useState是一种使用与 this.state 在类中提供的功能完全相同的功能的新方法这意味着它的核心仍然依赖于旧this.setState({})功能。如果你记得使用this.setState(),你就会知道它有一个可用的回调函数,可以这样使用:this.setState((currentState) => { /* do something with current state */ })现在已经转移到useStatehook 的第二个解构项[item, setItem] setItem,因此它具有相同的功能:setItem((currentState) => { /* do something with current state */ }

幕布斯6054654

通过钩子,React 包含每个状态名称到其当前值的内部映射。和const [todos, setTodos] = useState<Todo[]>([])每当setTodos调用并todos再次设置状态时,React 都会将内部状态更新为todos新值。useState调用时,它还将返回变量的当前内部状态。你可以这样想:// React internalslet internalState;const setState = (param) => {&nbsp; if (typeof param !== 'function') {&nbsp; &nbsp; internalState = param;&nbsp; } else {&nbsp; &nbsp; param(internalState);&nbsp; }};const useState = initialValue => {&nbsp; internalState ??= initialValue;&nbsp; return [internalState, setState];}然后,当您调用状态设置器时,您可以向它传递一个普通值(更新internalState),或者您可以向它传递一个函数,该函数在被调用时将当前内部状态作为第一个参数传递。请注意,该prevTodos参数将包含当前状态,包括中间更新。例如,如果您setTodos在重新渲染发生之前同步调用两次,则您需要第二次使用回调形式才能“看到”第一次调用setTodos.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript