React函数组件上的状态更新钩子不允许使用点表示法。

huangapple go评论98阅读模式
英文:

React update state hook on functional component does not allow dot notation

问题

我收到以下错误:

解析错误:意外的令牌,期望“,”

在我的功能组件(不是类)中,我有:

const [ministries, setMinistries] = useState({
  options: '',
  selected: ''
});

稍后在另一个方法中,我尝试通过以下方式更新ministries

let opts = [1, 2, 3, 4];

setMinistries({
  ministries.selected: opts
})

假设ministries是对象,而selected位于ministries中,我期望点表示法ministries.selected: opts能够工作。

我做错了什么?

英文:

I'm getting the following error:

Parsing error: Unexpected token, expected ","

In my functional component (not class) I have:

  const [ ministries, setMinistries ] = useState({
    options: '',
    selected: ''
  });

later in another method I try to update ministries by doing the following:

let opts = [1, 2, 3, 4];

setMinistries({
  ministries.selected: opts
})

Assuming ministries is the object and selected is in ministries I would expect dot notation.
ministries.selected: opts to work.

What am I doing wrong?

答案1

得分: 4

请注意,useState 的更新器会用新状态覆盖先前的状态,而不会执行任何合并操作。
相反,它要求你每次都传递完整的状态。

然而,在 class 组件 中,this.setState 不是这种情况。

这是我建议要记住的重要事情,以避免微妙的不希望的行为。

所以,更新状态的正确方式是:

setMinistries(prevMinistries => ({
   ...prevMinistries,
   selected: opts
}));
英文:

Please, be aware that the useState updater overwrite a previous state with a new one and it does not perform any merging.
Instead, it requires you to pass the complete state each time.

However, that's not the case with this.setState in a class component.

That's something that, to my advice, is important to remember to avoid subtle undesired behavior.

So, the correct way to update your state would be:

setMinistries(prevMinistries => ({
   ...prevMinistries,
   selected: opts
}));

答案2

得分: 0

你不能将 ministries.selected 作为对象键。

你只需这样做:

setMinistries({
  selected: opts,
});
英文:

You can't do ministries.selected as an object key.

You can just do:

setMinistries({
  selected: opts,
});

答案3

得分: 0

这是错误的语法。你在一个对象内部调用了对象的属性。

尝试:

setMinistries({
  ministries: {
    selected: opts
  }
})

或者

setMinistries({
  selected: opts
})
英文:
setMinistries({
  ministries.selected: opts
})

This is bad syntax. You call the property of the object within an object.

Try

setMinistries({
  ministries: {
    selected: opts
  }
})

or

setMinistries({
  selected: opts
})

huangapple
  • 本文由 发表于 2020年1月3日 16:20:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定