状态跟踪和钩子中的道具 - 钩子中的反应如何保持(跟踪)状态和道具?
我知道在React类中,React使用“ Track”道具和状态的“此”绑定。在钩子中,这要归功于封闭,我的疑问是吗?
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
此代码可以按照您期望的计数器进行操作,如果您使用类组件,则必须在回调模式下使用setState()访问先前的状态,,但在挂钩中,魔术是如何发生的?
<强>钩子上是否有任何绑定?
I know that in React class components React uses the "this" binding to "track" props and state. In hooks it is achieved thanks to closures, is my doubt?
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
This code works as you would expect a counter, if you were using class component you would have to use setState() in callback mode to access the previous state, but in hooks how does the magic happen?
are there any bindings on the hooks or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
React通过内部计数次数
USESTATE
首次安装次数来跟踪状态。然后将传递到usestate
的值设置为React的内部状态。例如,给定的React将在内部存储以下状态:
对于
usestate
的每个呼叫的(隐藏,内部)状态数组中的一个项目。当调用状态设置器时,内部状态数组中的相应项目将被更新,然后组件将重新渲染。当组件重新渲染时,每个
usestate
调用,然后在内部状态数组中返回适当的项目。第一个usestate
调用将返回内部状态数组中的第一个项目,第二个usestate
呼叫将返回第二项,依此类推。在您的代码中,使用钩子,点击处理程序对
count
的值进行了关闭,该值在该特定的计数器上存在。- 如果此代码是类组件,则可以免费参考
this.state.state.count.count
直接不使用回调版。React keeps track of state by internally counting the number of times
useState
is called the first time a component mounts. The value passed intouseState
is then set into React's internal state. For example, givenReact will then have the following state stored internally:
with one item in the (hidden, internal) state array for each call of
useState
that there is.When a state setter is called, the corresponding item in the internal state array will be updated, and then the component will re-render. When a component re-renders, each
useState
call then returns the appropriate item in the internal state array. The firstuseState
call will return the first item in the internal state array, the seconduseState
call will return the second item, and so on.In your code, with hooks, the click handler has a closure over the value of
count
that existed at that particular render of Counter.Not really - if this code was a class component, it would be free to reference
this.state.count
directly without using the callback version.