Javascript React 中的 useState() 是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53165945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is useState() in React?
提问by Hemadri Dasari
I am currently learning hooks concept in React and trying to understand below example.
我目前正在 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>
);
}
The above example increments the counter on the handler function parameter itself. What if I want to modify count value inside event handler function
上面的例子增加了处理函数参数本身的计数器。如果我想在事件处理函数中修改计数值怎么办
Consider below example
考虑下面的例子
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>
回答by Enmanuel Duran
React hooksare a new way (still being developed) to access the core features of react such as statewithout 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 onClickprop, you could do something like:
React hooks是一种新方法(仍在开发中)来访问 react 的核心功能,例如state无需使用类,在您的示例中,如果您想直接在处理程序函数中增加计数器而不直接在onClickprop 中指定它,您可以做这样的事情:
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
and onClick:
和点击:
<button onClick={setCount}>
Click me
</button>
Let's quickly explain what is going on in this line:
让我们快速解释一下这一行发生了什么:
const [count, setCounter] = useState(0);
useState(0)returns a tuple where the first parameter countis the current state of the counter and setCounteris the method that will allow us to update the counter's state. We can use the setCountermethod to update the state of countanywhere - In this case we are using it inside of the setCountfunction 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 componentsif not desired/needed.
useState(0)返回一个元组,其中第一个参数count是计数器的当前状态,并且setCounter是允许我们更新计数器状态的方法。我们可以使用该setCounter方法来更新count任何地方的状态- 在这种情况下,我们setCount在可以做更多事情的函数内部使用它;使用钩子的想法是,如果不需要/不需要,我们能够使我们的代码更具功能性,并避免基于类的组件。
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 hookand other hooks in detail, hope it helps.
我写了多个例子挂钩一个完整的文章(包括计数器)如本codepen,我利用了useState,useEffect,useContext,和自定义挂钩。我可以详细了解钩子如何在这个答案上工作,但文档很好地解释了状态钩子和其他钩子,希望它有所帮助。
update:Hooks are not longer a proposal, since version 16.8they're now available to be used, there is a section in React's site that answers some of the FAQ.
更新:Hooks 不再是一个建议,因为它们现在可以使用16.8版,React 站点中有一个部分回答了一些常见问题。
回答by loelsonk
useStateis one of build-in react hooks available in 0.16.7version.
useState是0.16.7版本中可用的内置反应钩子之一。
useStateshould be used only inside functional components. useStateis the way if we need an internal state and don't need to implement more complex logic such as lifecycle methods.
useState应该只在功能组件内部使用。useState如果我们需要一个内部状态并且不需要实现更复杂的逻辑(例如生命周期方法),这是一种方式。
const [state, setState] = useState(initialState);
Returns a stateful value, and a function to update it.
During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).
The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
返回一个有状态的值和一个更新它的函数。
在初始渲染期间,返回的状态 (state) 与作为第一个参数 (initialState) 传递的值相同。
setState 函数用于更新状态。它接受一个新的状态值并将组件的重新渲染排入队列。
Please notethat useStatehook callback for updating the state behaves differentlythan components this.setState. To show you the difference I prepared two examples.
请注意,useState用于更新状态的钩子回调的行为与组件不同this.setState。为了向您展示差异,我准备了两个示例。
class UserInfoClass extends React.Component {
state = { firstName: 'John', lastName: 'Doe' };
render() {
return <div>
<p>userInfo: {JSON.stringify(this.state)}</p>
<button onClick={() => this.setState({
firstName: 'Jason'
})}>Update name to Jason</button>
</div>;
}
}
// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
const [userInfo, setUserInfo] = React.useState({
firstName: 'John', lastName: 'Doe',
});
return (
<div>
<p>userInfo: {JSON.stringify(userInfo)}</p>
<button onClick={() => setUserInfo({ firstName: 'Jason' })}>Update name to Jason</button>
</div>
);
}
ReactDOM.render(
<div>
<UserInfoClass />
<UserInfoFunction />
</div>
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div>
New object is created when setUserInfocallback is used. Notice we lost lastNamekey value. To fixed that we could pass function inside useState.
setUserInfo使用回调时会创建新对象。注意我们丢失了lastName键值。为了修复我们可以在useState.
setUserInfo(prevState => ({ ...prevState, firstName: 'Jason' })
See example:
见示例:
// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
const [userInfo, setUserInfo] = React.useState({
firstName: 'John', lastName: 'Doe',
});
return (
<div>
<p>userInfo: {JSON.stringify(userInfo)}</p>
<button onClick={() => setUserInfo(prevState => ({
...prevState, firstName: 'Jason' }))}>
Update name to Jason
</button>
</div>
);
}
ReactDOM.render(
<UserInfoFunction />
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div>
Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:
setState(prevState => { // Object.assign would also work return {...prevState, ...updatedValues}; });
与类组件中的 setState 方法不同,useState 不会自动合并更新对象。您可以通过将函数更新程序形式与对象传播语法相结合来复制此行为:
setState(prevState => { // Object.assign would also work return {...prevState, ...updatedValues}; });
For more about useStatesee official documentation.
有关更多信息,useState请参阅官方文档。
回答by Jan Cio?ek
The syntax of useStatehook is straightforward.
useStatehook的语法很简单。
const [value, setValue] = useState(defaultValue)
const [value, setValue] = useState(defaultValue)
If you are not familiar with this syntax, go here.
如果您不熟悉此语法,请转到此处。
I would recommend you reading the documentation.There are excellent explanations with decent amount of examples.
我建议你阅读文档。有很好的解释和大量的例子。
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
// its up to you how you do it
const buttonClickHandler = e => {
// increment
// setCount(count + 1)
// decrement
// setCount(count -1)
// anything
// setCount(0)
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={buttonClickHandler}>
Click me
</button>
</div>
);
}
回答by codejockie
useStateis one of the hooks available in React v16.8.0. It basically lets you turn your otherwise non-stateful/functional components to one that can have its own state.
useState是 React v16.8.0 中可用的钩子之一。它基本上可以让您将其他无状态/功能组件转换为可以拥有自己状态的组件。
At the very basic level, it's used this way:
在最基本的层面上,它是这样使用的:
const [isLoading, setLoading] = useState(true);
This then lets you call setLoadingpassing a boolean value.
It's a cool way of having "stateful" functional component.
然后,您可以调用setLoading传递布尔值。这是拥有“有状态”功能组件的一种很酷的方式。
回答by Muhammad Shaheem
useState() is an example built-in React hook that lets you use states in your functional components. This was not possible before React 16.7.
useState() 是一个内置的 React 钩子示例,它允许您在功能组件中使用状态。这在 React 16.7 之前是不可能的。
The useState function is a built in hook that can be imported from the react package. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.
useState 函数是一个内置的钩子,可以从 react 包中导入。它允许您向功能组件添加状态。在函数组件中使用 useState 钩子,您可以在不切换到类组件的情况下创建一段状态。
回答by Asif vora
Hooks are a new feature in React v16.7.0-alphauseStateis the “Hook”. useState()set the default value of the any variable and manage in function component(PureComponent functions). ex : const [count, setCount] = useState(0);set the default value of count 0. and u can use setCountto incrementor decrementthe value. onClick={() => setCount(count + 1)}increment the count value.DOC
Hooks 是React v16.7.0-alphauseState“Hook”中的一个新特性。useState()设置任何变量的默认值并在函数组件(PureComponent 函数)中进行管理。 ex : const [count, setCount] = useState(0);设置计数 0 的默认值。您可以使用setCounttoincrement或decrement该值。onClick={() => setCount(count + 1)}增加计数值。文件
回答by geckos
useState()is a React hook. Hooks make possible to use state and mutability inside function components.
useState()是一个 React 钩子。钩子使在函数组件中使用状态和可变性成为可能。
While you can't use hooks inside classes you can wrap your class component with a function one and use hooks from it. This is a great tool for migrating components from class to function form. Here is a complete example:
虽然您不能在类中使用钩子,但您可以用函数 one 包装类组件并使用它的钩子。这是将组件从类迁移到函数形式的绝佳工具。这是一个完整的例子:
For this example I will use a counter component. This is it:
对于这个例子,我将使用一个计数器组件。就是这个:
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { count: props.count };
}
inc() {
this.setState(prev => ({count: prev.count+1}));
}
render() {
return <button onClick={() => this.inc()}>{this.state.count}</button>
}
}
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>
It is a simple class component with a count state, and state update is done by methods. This is very common pattern in class components. The first thing is to wrap it with a function component with just the same name, that delegate all its properties to the wrapped component. Also you need to render the wrapped component in the function return. Here it is:
它是一个简单的带有计数状态的类组件,状态更新是通过方法来完成的。这是类组件中非常常见的模式。首先是用一个同名的函数组件包装它,将它的所有属性委托给被包装的组件。您还需要在函数返回中呈现包装的组件。这里是:
function Hello(props) {
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { count: props.count };
}
inc() {
this.setState(prev => ({count: prev.count+1}));
}
render() {
return <button onClick={() => this.inc()}>{this.state.count}</button>
}
}
return <Hello {...props}/>
}
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>
This is exactly the same component, with the same behavior, same name and same properties. Now lets lift the counting state to the function component. This is how it goes:
这是完全相同的组件,具有相同的行为、相同的名称和相同的属性。现在让我们将计数状态提升到函数组件。事情是这样的:
function Hello(props) {
const [count, setCount] = React.useState(0);
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { count: props.count };
}
inc() {
this.setState(prev => ({count: prev.count+1}));
}
render() {
return <button onClick={() => setCount(count+1)}>{count}</button>
}
}
return <Hello {...props}/>
}
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>
<div id='root'></div>
Note that the method incis still there, it wont hurt anybody, in fact is dead code. This is the idea, just keep lifting state up. Once you finished you can remove the class component:
注意方法inc还在,不会伤害任何人,实际上是死代码。这就是想法,只是保持提升状态。完成后,您可以删除类组件:
function Hello(props) {
const [count, setCount] = React.useState(0);
return <button onClick={() => setCount(count+1)}>{count}</button>;
}
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>
<div id='root'></div>
While this makes possible to use hooks inside class components, I would not recommend you to do so except if you migrating like I did in this example. Mixing function and class components will make state management a mess. I hope this helps
虽然这使得在类组件中使用钩子成为可能,但我不建议你这样做,除非你像我在这个例子中所做的那样迁移。混合使用函数和类组件会使状态管理变得一团糟。我希望这有帮助
Best Regards
此致
回答by Янов Алексей
Thanks loelsonk, i did so
谢谢 loelsonk,我这样做了
const [dataAction, setDataAction] = useState({name: '', description: ''});
const _handleChangeName = (data) => {
if(data.name)
setDataAction( prevState => ({ ...prevState, name : data.name }));
if(data.description)
setDataAction( prevState => ({ ...prevState, description : data.description }));
};
....return (
<input onChange={(event) => _handleChangeName({name: event.target.value})}/>
<input onChange={(event) => _handleChangeName({description: event.target.value})}/>
)
回答by Abhishek Kumar
useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:import React, {useState} from react
function HookCounter {
const [count, stateCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count} </button>
</div>
)
}
useState 是一个钩子,可让您向功能组件添加状态。它接受一个参数,它是 state 属性的初始值,并返回 state 属性的当前值和一个能够更新该 state 属性的方法。
下面是一个简单的例子:import React, {useState} from react
function HookCounter {
const [count, stateCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count} </button>
</div>
)
}
useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.
useState 接受状态变量的初始值,在这种情况下为零,并返回一对值。状态的当前值被称为 count,并且可以更新状态变量的方法被称为 setCount。

