setState不会在React Js中更新数组状态

时间:2020-08-29 14:40:18

标签: javascript reactjs react-component

我尝试从输入中获取值并将其放入对象中,然后推送到新数组。然后将此数组(与setState)与我的状态数组组合。但是,我的状态数组值始终返回空。你能说出哪里出了问题吗。谢谢。

/Users/stavalfi/projects/nc/node_modules/winston/node_modules/readable-stream/lib/_stream_writable.js:261
  var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
           ^
Error: write after end
    at writeAfterEnd (/Users/stavalfi/projects/nc/node_modules/winston/node_modules/readable-stream/lib/_stream_writable.js:261:12)
    at DerivedLogger.Writable.write (/Users/stavalfi/projects/nc/node_modules/winston/node_modules/readable-stream/lib/_stream_writable.js:305:21)
    at DerivedLogger.value (/Users/stavalfi/projects/nc/node_modules/winston/lib/winston/logger.js:67:18)
    at DerivedLogger.<computed> [as info] (/Users/stavalfi/projects/nc/node_modules/winston/lib/winston/create-logger.js:81:14)
    at Object.info (/Users/stavalfi/projects/nc/packages/log/src/loggers.ts:47:11)
    at /Users/stavalfi/projects/nc/packages/nc/src/index.ts:23:11

2 个答案:

答案 0 :(得分:0)

第一件事是,您不应该期望在使用console.log()之后立即看到setState()在该行中的更改,因为这是异步操作。

您还可以尝试使用数组的先前状态并传递obj而不是SeassionList

this.setState(prevState => ({
   ...prevState,
   seassions: [...prevState.seassions, obj]
}))

答案 1 :(得分:0)

由于@norbitrial提到setState是异步操作,因此console.log()将不会显示更新后的状态。如果要检查状态是否正在更新,则可以使用setState方法提供的回调,如下所示:

this.setState(prevState => ({
      seassions: [...prevState.seassions, SeassionList[0]]
    }),() => {
    console.log(this.state.seassions);
})