简体   繁体   English

useState 不会更新状态

[英]useState won't update state

I'm trying to update a state using useState hook, however the state won't update.我正在尝试使用useState钩子更新状态,但是状态不会更新。

const handleSelect = address => {
    geocodeByAddress(address)
      .then(address => {
        const receivedAddress = address[0];
        const newAddress = {
          street: receivedAddress.address_components[1].long_name,
          number: receivedAddress.address_components[0].long_name,
          city: receivedAddress.address_components[3].long_name,
          country: receivedAddress.address_components[5].long_name,
          zip: receivedAddress.address_components[6].long_name,
          selected: true
        };
        handleAddressSelection(newAddress);
      })
      .catch(error => console.log(error));
  };

When handleSelect is called, it creates the object newAddress , and then calls handleAddressSelection passing newAddress .handleSelect被调用时,它会创建对象newAddress ,然后通过newAddress调用handleAddressSelection

function handleAddressSelection(newObj) {
    console.log(newObj);
    Object.keys(newObj).forEach(function(key) {
      setValues({ ...values, [key]: newObj[key] });
    });
  }

In console.log(newObj) the object is filled fine, with all the data I need.console.log(newObj) ,对象填充得很好,包含我需要的所有数据。 Then I call setValues for each object in newObj , however no matter what, the values object won't receive the new data.然后我为newObj每个对象调用setValues ,但是无论如何, values对象都不会接收新数据。 The only one that is updated is selected: true , all others won't update.选择了唯一更新的selected: true ,所有其他人都不会更新。

What should I do to fix it?我应该怎么做才能修复它?

You're calling setValues multiple times in a loop, and every time you do so, you spread the original values, and thus overwrite anything that was done on the previous setValues.您在循环中多次调用 setValues,每次调用时,您都会传播原始值,从而覆盖在先前 setValues 上所做的任何事情。 Only the very last setValues ends up working, which happens to be the one for selected: true只有最后一个 setValues 结束工作,这恰好是selected: true那个

If you need to base your update on the previous value of the state, you should use the function version of setValues, as in:如果您需要根据状态的先前值进行更新,则应使用 setValues 的函数版本,如下所示:

Object.keys(newObj).forEach(function(key) {
  setValues(oldValues => ({ ...oldValues, [key]: newObj[key] }));
});

But even better would be to only call setValues once.但更好的是只调用 setValues 一次。 If you're calling it multiple times, then you're going to generate multiple renders.如果您多次调用它,那么您将生成多个渲染。 I'd do this:我会这样做:

setValues(oldValues => ({...oldValues, ...newObj}));

Values is not even defined anywhere in your examples. Values 甚至没有在您的示例中的任何地方定义。 My guess is, it's some cached copy and you should be using callback variant of the state setter instead:我的猜测是,它是一些缓存副本,您应该使用状态设置器的回调变体:

setValues(previousValues => ({ ...previousValues, [key]: newObj[key] }));

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

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