简体   繁体   English

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

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

I am trying to use redux value to set an initial state of react component using useState.when I am trying to set the state of setIsStar it says currentChannelName is null.我正在尝试使用 redux 值来设置使用 useState 的 react 组件的初始状态。当我尝试设置 setIsStar 的状态时,它说 currentChannelName 为 null。 How can I avoid this?我怎样才能避免这种情况? or is there any other way或者有没有其他方法

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


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

Possible solution is to combine it with useEffect :可能的解决方案是将它与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
}: {});

` `

You should avoid this as it dilutes your state across two separate domains.您应该避免这种情况,因为它会在两个不同的域中稀释您的状态。

Keep app-wide state in your redux store, keep local component state in your components.在您的 redux 存储中保持应用程序范围的状态,在您的组件中保持本地组件状态。

If you really do want to do this, you'll probably just have to deal with the initial case where your component has mounted but the store is not populated with the data you need.如果您真的想这样做,您可能只需要处理您的组件已安装但存储未填充您需要的数据的初始情况。

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

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

The easiest solution would be:最简单的解决方案是:

// 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