繁体   English   中英

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

[英]how can we use redux state in useState to set initial values

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

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


  const [isStar, setIsStar] = useState({
    [currentChannelName]: true
  });

可能的解决方案是将它与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
}: {});

`

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

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

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

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

const [isStar, setIsStar] = useState(currentChannelName && {
  [currentChannelName]: true
});

最简单的解决方案是:

// Redux state
const user = useSelector((state) => state.user);

const [firstName, setFirstName] = useState(user.firstName || '');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM