如何使用 React 获取扩展运算符更新状态

Pet*_*ner 1 javascript reactjs

我在 Component 中定义了我的初始状态,如下所示:

constructor(props) {
    super(props);
    //this.state = {count: props.initialCount};
    this.state = {
        timeArray: [],
        metawords: '',
        description: '',
        currentTime: '',
        inputFieldsDisabled: true
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个被调用的事件,我只想更新元词属性。我在想下面的代码应该可以工作,但事实并非如此。

updateInputValue1(evt) {
    const newMetawords = "abcd";
    this.setState(
        [...this.state,{
            metawords: evt.target.value
        }]
    );
Run Code Online (Sandbox Code Playgroud)

想法?

mer*_*lin 9

state 是一个对象,因此以您目前的方式更新它是行不通的。

您可以简单地仅更新您需要的属性:

this.setState({
  metawords: evt.target.value,
})
Run Code Online (Sandbox Code Playgroud)

由于您已经提到了spread运营商,您还可以(但并非总是必要)将您的状态更新为:

this.setState({
  ...this.state,
  metawords: evt.target.value,
})
Run Code Online (Sandbox Code Playgroud)

或者

this.setState(prevState => ({
  ...prevState,
  metawords: evt.target.value,
}))
Run Code Online (Sandbox Code Playgroud)

如果您需要更多信息,我建议您查看ReactJS 文档