我目前正在学习React中的钩子概念,并试图理解下面的例子。
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
上面的示例增加了处理程序函数参数本身的计数器。如果我想修改事件处理函数内的计数值怎么办
考虑下面的例子:
setCount = () => {
//how can I modify count value here. Not sure if I can use setState to modify its value
//also I want to modify other state values as well here. How can I do that
}
<button onClick={() => setCount()}>
Click me
</button>
基本上React.useState(0)神奇地看到它应该返回元组计数和setCount(一个改变计数的方法)。参数useState用于设置count的初始值。
const [count, setCount] = React.useState(0);
const [count2, setCount2] = React.useState(0);
// increments count by 1 when first button clicked
function handleClick(){
setCount(count + 1);
}
// increments count2 by 1 when second button clicked
function handleClick2(){
setCount2(count2 + 1);
}
return (
<div>
<h2>A React counter made with the useState Hook!</h2>
<p>You clicked {count} times</p>
<p>You clicked {count2} times</p>
<button onClick={handleClick}>
Click me
</button>
<button onClick={handleClick2}>
Click me2
</button>
);
基于Enmanuel Duran的示例,但显示了两个计数器,并将lambda函数作为普通函数编写,因此有些人可能更容易理解。
React钩子是一种新的方式(仍在开发中)来访问React的核心功能,如状态,而不必使用类,在你的例子中,如果你想直接在处理程序函数中增加一个计数器,而不直接在onClick道具中指定它,你可以这样做:
...
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、useEffect、useContext和自定义钩子。我可以更详细地介绍钩子如何在这个答案上工作,但是文档很好地解释了状态钩子和其他钩子的细节。
更新:钩子不再是一个建议,因为16.8版本他们现在可以使用,在React的网站上有一个部分回答了一些常见问题。