我正在尝试在我的应用程序中显示频道的实时列表,这是给我错误的代码-
function Sidebar() {
const user = useSelector(selectUser);
const [channels, setChannels] = useState([]);
useEffect(() => {
db.collection("channels").onSnapshot((snapshot) => {
setChannels(
snapshot.docs.map((doc) => ({
id: doc.id,
channel: doc.data(),
}))
);
});
}, []);
const addChannel = () => {
const channelName = prompt("Enter channel name");
if (channelName) {
db.collection("channels").add({
channelName,
});
}
};
return (
<div className="sidebar">
<div className="sidebar_top">
<h3>Discord Clone</h3>
<ExpandMoreIcon className="expandMoreIcon" />
</div>
<div className="sidebar_channels">
<div className="sidebarChannels_header">
<div className="header">
<ExpandMoreIcon className="expandMoreIcon" />
<h4>Text Channels</h4>
</div>
<IconButton className="IconButton">
<AddIcon className="addIcon" onClick={addChannel} />
</IconButton>
</div>
<div className="sidebar_channelList">
{channels.map(({ id, channel }) => (
<SidebarChannel
key={id}
id={id}
channelName={channel.channelName}
/>
))}
</div>
</div>
<div className="sidebar_voice">
<SignalCellularAltIcon className="voiceIcon" />
<div className="sidebar_voiceInfo">
<h4>Voice Connected</h4>
<p>Stream</p>
</div>
<div className="sidebar_voiceIcons">
<InfoIcon className="icon" />
<CallIcon className="icon" />
</div>
</div>
<div className="sidebar_profile">
<Avatar onClick={() => auth.signOut()} src={user.photo} />
<div className="sidebar_profileInfo">
<h4>{user.displayName}</h4>
<p>#{user.uid.substring(0, 5)}</p>
</div>
<div className="sidebar_profileIcons">
<MicIcon className="icon" />
<HeadsetIcon className="icon" />
<SettingsIcon className="icon" />
</div>
</div>
</div>
);
}
export default Sidebar;
在我创建一个新频道后,我得到了这个错误-错误:对象作为React子对象无效(已找到:具有键{}的对象(。如果要渲染子对象的集合,请改用数组
知道是什么导致了这个错误吗?提前谢谢。
是否检查了您的状态设置是否正确?您正确初始化通道状态:
const [channels, setChannels] = useState([]);
您的state.channels在更新后仍然是一个有效的数组吗?
如果你还没有使用React Developer Tools for Chrome,我建议你查看一下。它可以让你在运行的应用程序中查看自己的状态:https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi