简体   繁体   English

如何使用 react 和 json-server 更新嵌套对象

[英]how to update nested object using react and json-server

I really need some help I am trying to figure out the issue for three days but no luck so if you can help I would really appreciated ....I am trying to build a simple app with react and json-server for back end the issue I am having the data has nested object so when even I fetch the data and try to modified it is throw error says the kay in nested obj undefined !!我真的需要一些帮助我正在尝试解决这个问题三天但没有运气所以如果你能帮助我真的很感激......我正在尝试构建一个简单的应用程序,使用 react 和 json-server 作为后端问题我有数据有嵌套对象,所以即使我获取数据并尝试修改它时也会抛出错误说嵌套对象中的 kay undefined ! the question how to update the state has nested obj the is the user state const [getUser, setGetUser] = useState({ first_name: '', last_name: '', age: '', gender: '', address: { address1: '', address2: '', city: '', state: '', zip: '' }, order_total: { amount: 0 }, });如何更新状态的问题已嵌套 obj 是用户状态 const [getUser, setGetUser] = useState({ first_name: '', last_name: '', age: '', sex: '', address: { address1: '', address2: '', city: '', state: '', zip: '' }, order_total: { amount: 0 }, }); and this how onChnage fun works setGetUser({ ...getUser, [e.target.name]: e.target.value }) let see I want to update city in address obj how I can do that这如何 onChnage fun 工作 setGetUser({ ...getUser, [e.target.name]: e.target.value }) 让我们看看我想更新地址 obj 中的城市我怎么做

When you write:当你写:

setGetUser({ ...getUser, [e.target.name]: e.target.value })

You are adding a new key value pair to the dictionary, not updating an existing one.您正在向字典中添加一个新的键值对,而不是更新现有的键值对。 If you want to update an existing key value pair, for example the city, you should try the following:如果您想更新现有的键值对,例如城市,您应该尝试以下操作:

  • Clone the dictionary克隆字典
  • Amend the clone with the new info使用新信息修改克隆
  • setState(amended cloned dictionary) setState(修改后的克隆字典)

Eg:例如:

  const [getUser, setUser] = useState({
    first_name: "",
    last_name: "",
    age: "",
    gender: "",
    address: {
      address1: "",
      address2: "",
      city: "",
      state: "",
      zip: ""
    },
    order_total: {
      amount: 0
    }
  });

const updateCityHandler = (city) => {
    let newDict = {...getUser}
    newDict.address.city = city
    setGetUser(newDict)
}

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

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