简体   繁体   English

如何更新 React state(功能组件)中的单个属性

[英]How to update a single property in a React state (function component)

I want to update a state with a couple of values from a form with a single change handler in a function component.我想用 function 组件中的单个更改处理程序的表单中的几个值来更新 state。 I cannot figure out how to set a single property in the state in a proper way.我无法弄清楚如何以正确的方式在 state 中设置单个属性。 I have seen this works in a class component.我已经在 class 组件中看到了此功能。

import React, {useState} from 'react'
import ReactDOM from 'react-dom'

export function Example(){
  const [user, setUser] = useState({nickname: '', age: 0})

  const handleChange = event => {
    const { name, value } = event.target
    setUser({ [name]: value })
  }

  return(
     <form>
       <input name="nickname" onChange={handleChange} />
       <input name="age" onChange={handleChange} />
       <button onClick={(e) => {
         e.preventDefault()
         console.log(user)
        }}>Show User</button>
     </form>
  )
}

ReactDOM.render(
    <Example />,
    document.getElementById('app')
);

The code above does not work the way I want to since it always overrides the whole state and not only the corresponding property.上面的代码不能按我想要的方式工作,因为它总是覆盖整个 state 而不仅仅是相应的属性。

I receive:我收到:

Object {age: "24"}
Object {nickname: "Lala"}

I want:我想:

Object {age: "24", nickname: "Lala"}

What is the best practice to achieve this?实现这一目标的最佳实践是什么?

Try to do it this way: 尝试通过以下方式进行操作:

const handleChange = event => {
    const { name, value } = event.target
    setUser({ ...user, [name]: value })
}

Actually you are very close to the solution in the following line 实际上,您非常接近以下行中的解决方案

  setUser({ [name]: value })

But you need to ensure the persistency of the legacy values that this input doesn't touch, therefore you need to change it to 但是您需要确保此输入不会触及的旧值的持久性,因此需要将其更改为

  setUser({ ...user, [name]: value })

const [state,setSate]={data1:"d1",data2:"d2",.....}常量 [state,setSate]={data1:"d1",data2:"d2",.....}

now we can call the statement in appropriate callback function(consider to update data1 & data2):现在我们可以在适当的回调函数中调用该语句(考虑更新 data1 和 data2):

onChange={(e)=>{
    setState((state)=>{return ({...state, data1: e.target.value,data2: e.target.value, }) })
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM