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

时间:2019-07-12 15:50:18

标签: 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
  });

2 个答案:

答案 0 :(得分:2)

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

`

答案 1 :(得分:0)

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

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

如果您确实想执行此操作,则可能只需要处理最初的情况,即您的组件已装入,但存储中未填充所需的数据。

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

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