且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React中的useState()是什么?

更新时间:2023-01-13 23:18:46

反应钩子是一种新方法(仍在开发中),无需使用类即可访问诸如state之类的react核心功能,在您的示例中,如果您想直接在处理函数中增加计数器而不直接在 prop,您可以执行以下操作:

React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

和onClick:

<button onClick={setCount}>
    Click me
</button>

让我们快速解释此行中发生的事情:

const [count, setCounter] = useState(0);

useState(0)返回一个元组,其中第一个参数count是计数器的当前状态,而setCounter是允许我们更新计数器状态的方法.我们可以在任何地方使用setCounter方法更新count的状态-在这种情况下,我们在setCount函数内部使用它可以做更多的事情;带有钩子的想法是,我们能够使代码保持更多功能,并且在不需要/不需要时,避免使用基于基于类的组件.

useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

我写了一篇完整的文章,介绍了带有多个示例的钩子(包括计数器),例如此codepen ,我使用了useStateuseEffectuseContext自定义钩子.我可以深入了解钩子如何在此答案上工作,但是文档在解释详细说明钩子和其他钩子,希望对您有所帮助.

I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail, hope it helps.

更新:挂钩不再是建议,因为版本 16.8 现在可以使用了,React网站上有一个部分可以回答一些

update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.