将新元素插入空的 JSON 对象

我正在尝试将数据插入一个空的 JSON 数组,但遇到了问题。我在构造函数中定义数组,然后在页面加载时向后端发出几个 get 请求,在获得响应后,我想将新的数组元素添加到现有元素中。这是我正在使用的代码:


constructor() {

        super();

        this.state = {

            sds: []

        }

    }


    componentDidMount() {

      axios.get('/userData', {

          params: {

              user: this.props.auth.user.name

          }

      }).then(res => {

        for(var i=0; i<res.data[0].chemID.split(',').length; i++){

          if(res.data[0].chemID.split(',')[i] != 0){

              axios.get('/chemData', {

              params: {

                id: res.data[0].chemID.split(',')[i]

              }

             //This is where I want to insert the data

            }).then(res => this.sds += ({

              id: i,

              title: res.data[0].chemName,

              selected: false,

              key: 'sds'

            }))

          }          

        }

      })

  }


aluckdog
浏览 195回答 3
3回答

扬帆大鱼

+=不是那样工作的。使用扩展运算符复制数组的先前内容,然后手动添加新对象 -}).then((res) => {&nbsp; const newThing = {&nbsp; &nbsp; id: i,&nbsp; &nbsp; title: res.data[0].chemName,&nbsp; &nbsp; selected: false,&nbsp; &nbsp; key: 'sds'&nbsp; };&nbsp; this.setState(prevState => ({&nbsp; &nbsp; sds: [...prevState.sds, newThing]&nbsp; }))}你永远不应该尝试自己改变状态,总是使用setState. 在这种情况下,您可以传递一个函数作为第一个参数,它提供以前的状态。这样,您可以确保this.state.sds保留所有内容,并将新对象添加到该数组中。

慕标5832272

您可以尝试使用下一个示例:this.state.sds[this.state.sds.length] = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id: i,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title: res.data[0].chemName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key: 'sds'&nbsp; &nbsp; &nbsp; &nbsp; }[编辑]就像@larz 所说的那样,您必须使用 setState 方法来避免代码的意外结果。var newSds = this.stage.sds;newSds[newSds.length] = {&nbsp; &nbsp; &nbsp; id: i,&nbsp; &nbsp; &nbsp; title: res.data[0].chemName,&nbsp; &nbsp; &nbsp; selected: false,&nbsp; &nbsp; &nbsp; key: 'sds'&nbsp; &nbsp; };this.setState({ sds: newSds});你可以得到有关反应生命周期的详细信息在这里和“状态更新被合并”在这里
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript