[英]How to set states separately when an initial state is used to initiate several states at once with useState hook?
I'm trying to initiate several states at the same time using an intialState
with useState
hook, and they are set separately on several click events.我正在尝试使用带有
useState
钩子的intialState
同时启动多个状态,并且它们是在多个单击事件上分别设置的。 Check the following example:检查以下示例:
const {useState} = React; const Example = () => { const initialState = { name: 'Tom', age: 30, id: 1 }; const [state, setState] = useState(initialState) const handleClickName = (e) => { setState({ name: 'John', age, id }) } const handleClickAge = () => { setState({ name, age: 24, id }) } const handleClickId = () => { setState({ name, age, id: 2 }) } const { name, age, id } = state; return ( <div> <p>{name}</p> <p>{age}</p> <p>{id}</p> <button onClick={handleClickName}>Click 1</button> <button onClick={handleClickAge}>Click 2</button> <button onClick={handleClickId}>Click 3</button> </div> ) } // Render it ReactDOM.render( <Example/>, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>
This works well, clicking each button would update one state.这很有效,单击每个按钮将更新一个状态。 However the problem is in the
setState
function I have to include all properties like setState({ name: 'John', age, id })
.然而问题出在
setState
函数中,我必须包含所有属性,如setState({ name: 'John', age, id })
。 If there are lots of key/value pairs, it would be cumbersome to repeat everywhere.如果有很多键/值对,到处重复会很麻烦。
Is there a way to only update the required property without including all properties, like setState({ name: 'John' })
?有没有办法只更新所需的属性而不包括所有属性,比如
setState({ name: 'John' })
? I tried setState({ name: 'John'})
and it replaced the state with only name
property ( age
and id
are removed).我尝试了
setState({ name: 'John'})
并且它只用name
属性替换了 state( age
和id
被删除)。
rest operator
to your rescue: rest operator
来拯救你:
const handleClickName = (e) => {
setState({
...state,
name: 'John'
})
}
Alternatively, you could a class component
whose state updates works as you expect here.或者,您可以使用一个
class component
其状态更新按您的预期工作。
You can use the spread operator for that.您可以为此使用扩展运算符。
setState({...state, name: 'john'})
What this does is create a copy of all the other key/values in the state object and only replace the ones you name in the object.这样做是创建状态对象中所有其他键/值的副本,并仅替换您在对象中命名的键/值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.