Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在React中添加到嵌套数组?_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript 如何在React中添加到嵌套数组?

Javascript 如何在React中添加到嵌套数组?,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我正在构建一个松弛克隆原型。当我尝试将消息添加到数组this.state.channels.message时,它会将其作为新对象添加到数组通道中: 预期结果 class App extends React.Component { state = { channels : [ { id: 1, name: 'react', messages: ['React message 1', '**DESIRED MESSAGE**']}, { id: 2, name

我正在构建一个松弛克隆原型。当我尝试将消息添加到数组this.state.channels.message时,它会将其作为新对象添加到数组通道中:

预期结果

class App extends React.Component {
state = {
    channels : [
        { id: 1, name: 'react', messages: ['React message 1', '**DESIRED MESSAGE**']},
        { id: 2, name: 'react-router', messages: ['react-router message 1']},
    ],
当前结果

class App extends React.Component {
state = {
    channels : [
        { id: 1, name: 'react', messages: ['React message 1']},
        { id: 2, name: 'react-router', messages: ['react-router message 1']},
        { id: 1, messages: '**DESIRED MESSAGE**'}
    ],
更新组件状态的逻辑

handleSentMessage = (value) => {
    const {selectedChannelId, selectedPersonId, channels} = this.state;

    if(this.state.selectedChannelId) {
      this.setState({
        ...this.state,
          channels: [
            ...this.state.channels,
            this.state.channels[selectedChannelId-1].messages.push(value)
          ]
        }
      );
    }

    if(this.state.selectedPersonId) {
      this.setState({
        ...this.state,
          people: [
            ...this.state.people,
            this.state.people[selectedPersonId-1].messages.push(value)
          ]
        }
      );
    }
}
任何帮助都将不胜感激! github
您的
传播
频道不正确,因为第二条语句不会覆盖任何内容(它是
数组
不是
对象
)。当
频道
索引
等于
selectedChannelId-1时,使用
map
,并且仅使用
concat
消息

this.setState(prevState =>({
    channels : prevState.channels.map((channel,i) =>{
        if(i === selectedChannelId -1) return {
            ...channel,
            messages: channel.messages.concat('foo') //Now you overwrite it
        }

        return channel
    })
}))
您也可以直接使用
id
查找正确的
频道
,这样您就不再需要
selectedChannelId-1
,只需
selectedChannelId

可能重复的