我们如何在 useState 中使用 redux state 来设置初始值

Eva*_*Eva 9 reactjs redux react-hooks

我正在尝试使用 redux 值来使用 useState 设置 React 组件的初始状态。当我尝试设置 setIsStar 的状态时,它说 currentChannelName 为 null。我怎样才能避免这种情况?或者还有其他方法吗

const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;
  
const [isStar, setIsStar] = useState({
    [currentChannelName]: true
});
Run Code Online (Sandbox Code Playgroud)

小智 5

可能的解决方案是将其与useEffect

const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;

useEffect(() => {
    if(currentChannelName) {
        setIsStar({[currentChannelName]: true});
    }
}, [currentChannelName]); // listen only to currentChannelName changes

const [isStar, setIsStar] = useState(currentChannelName ? {
    [currentChannelName]: true
}: {});
Run Code Online (Sandbox Code Playgroud)

`


Wil*_*ins 4

您应该避免这种情况,因为它会在两个不同的域中稀释您的状态。

将应用程序范围的状态保存在您的 redux 存储中,将本地组件状态保存在您的组件中。

如果您确实想这样做,您可能只需要处理组件已安装但存储区未填充您需要的数据的初始情况。

const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;

const [isStar, setIsStar] = useState(currentChannelName && {
  [currentChannelName]: true
});
Run Code Online (Sandbox Code Playgroud)