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)代码>我看到我的新频道和所有的键和值。当Iconsole.log(现有通道)时
我看到所有添加了我的newChannel
的数组,但是所有类别都是未定义的
,当我控制台时,log(channels)
我的整个newChannel
对象没有添加,所有类别都是未定义的
是否有人看到此代码有任何错误,或者问题最有可能来自其他地方?不清楚为什么类别未定义。但是您不能在setChannels
之后立即控制台channels
,因为数据不会已经更新
使用useffect
记录数据。。或者,如果您在返回中循环它们,您会发现它已更新
useEffect(() => {
console.log(channels)
}, [channels]);
React set states是异步的,因此设置状态后直接进行控制台日志记录将显示旧值。好的,谢谢,我将使用channels
进行尝试,并查看是否实际添加了我的newChannel
。