如何更新嵌套状态对象的键/值(React JS)

当用户在表单中键入时,我试图更新状态中嵌套对象的键/值对。我的状态看起来像这样:


constructor(props) {

super(props);

this.state = {

  details: {

    detail1: {

      title: "",

      description: "",

      image1: null,

      image2: null,

    },

    detail2: {

      title: "",

      description: "",

      image1: null,

      image2: null,

    },

   detail3: {

      title: "",

      description: "",

      image1: null,

      image2: null,

    },

  },

};


}

这是我的渲染方法:


<form>

      <input

        type="text"

        value={this.state.creatives.creative1.title}

        onChange={(e) => {

          this.setState((prevState) => ({

            creatives: {

              ...prevState.creatives,

              creative1: {

                ...prevState.creatives.creative1,

                title: e.target.value,

              },

            },

          }));

          console.log(this.state.details.detail1.title);

        }}

      ></input>

    </form>

我尝试在 onChange 方法中更新上面的键/值,但控制台说我无法在 null 上调用 .target。由于某种原因, event.target 返回 null,我不确定为什么。如果有人有更好的解决方案来添加键入的值来更新状态,请提供帮助。


皈依舞
浏览 40回答 1
1回答

慕少森

传递给 onChange 的事件是一个综合事件。您不能以异步方式使用此类事件,因为 React 将重用该事件。setState以异步方式调用更新程序函数。如果您将事件值存储在常量中并在 中访问它setState,它应该可以工作。https://reactjs.org/docs/events.htmlhttps://reactjs.org/docs/react-component.html#setstateonChange={(e) => {&nbsp; &nbsp;const value = e.target.value&nbsp; &nbsp;this.setState((prevState) => ({&nbsp; &nbsp; &nbsp; &nbsp;creatives: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...prevState.creatives,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; creative1: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...prevState.creatives.creative1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title: value,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; }));&nbsp; &nbsp; &nbsp; console.log(this.state.details.detail1.title);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5