Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.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 首先展开数组后向其添加新对象时数组未更新_Javascript_Reactjs - Fatal编程技术网

Javascript 首先展开数组后向其添加新对象时数组未更新

Javascript 首先展开数组后向其添加新对象时数组未更新,javascript,reactjs,Javascript,Reactjs,单击一个按钮,我想更新我的频道阵列,并添加一个新频道,但它不工作。下面是更新数组时执行的函数 const channelData = setupChannels(venue !== null ? venue.chatRooms : []); const [channelName, setChannelName] = useState(''); const [categoryName, setCategoryName] = useState(''); const [channel

单击一个按钮,我想更新我的
频道
阵列,并添加一个新频道,但它不工作。下面是更新数组时执行的函数

  const channelData = setupChannels(venue !== null ? venue.chatRooms : []); 
  const [channelName, setChannelName] = useState('');
  const [categoryName, setCategoryName] = useState('');
  const [channels, setChannels] = useState(channelData);``` 

const onAddChannelClick  = () => {
    if (channelName === '') {
      return;
    }
    let existingChannels = [...channels];
    let newChannel = {
      key: existingChannels.length,
      name: channelName,
      deletable: true,
      markedForDelete: false,
      category: categoryName
    };
    existingChannels.push(newChannel);
    console.log(newChannel);
    setChannels(existingChannels);
    setChannelName('');
    setCategoryName('');
    setCreateChannel(false);
    console.log(existingChannels);
    console.log(channels);
  };
在第一个控制台日志中
console.log(newChannel)我看到我的新频道和所有的键和值。当I
console.log(现有通道)时
我看到所有添加了我的
newChannel
的数组,但是所有
类别都是
未定义的
,当我
控制台时,log(channels)
我的整个
newChannel
对象没有添加,所有
类别都是
未定义的


是否有人看到此代码有任何错误,或者问题最有可能来自其他地方?

不清楚为什么
类别
未定义。但是您不能在
setChannels
之后立即控制台
channels
,因为数据不会已经更新

使用
useffect
记录数据。。或者,如果您在
返回中循环它们,您会发现它已更新

useEffect(() => {
   console.log(channels)
}, [channels]);

React set states是异步的,因此设置状态后直接进行控制台日志记录将显示旧值。好的,谢谢,我将使用
channels
进行尝试,并查看是否实际添加了我的
newChannel