【问题标题】:how can we use redux state in useState to set initial values我们如何在 useState 中使用 redux state 来设置初始值
【发布时间】:2019-11-22 10:00:26
【问题描述】:

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

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


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

【问题讨论】:

    标签: reactjs redux react-hooks


    【解决方案1】:

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

    在你的 redux 商店中保持应用范围的状态,在你的组件中保持本地组件状态。

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

    const currentChannel = useSelector(state => state.channel.currentChannel);
    const currentChannelName = currentChannel.name;
    
    const [isStar, setIsStar] = useState(currentChannelName && {
      [currentChannelName]: true
    });
    

    【讨论】:

      【解决方案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
      }: {});
      

      `

      【讨论】:

        【解决方案3】:

        最简单的解决方案是:

        // Redux state
        const user = useSelector((state) => state.user);
        
        const [firstName, setFirstName] = useState(user.firstName || '');
        

        【讨论】:

        • // Redux state const flash = useSelector((state) => state.flash); useEffect(() => { const { is_loading, is_success, is_error, is_finally, items, errors } = flash; if (is_loading) { console.log("REDUX UPDATE is_loading VALUE " + is_loading); } else if (is_success) { console.log("REDUX UPDATE is_success VALUE " + is_success); } else if (is_error) { console.log("REDUX UPDATE is_error VALUE " + is_error); } }, [flash]);
        猜你喜欢
        • 1970-01-01
        • 2022-01-14
        • 2020-03-08
        • 2021-12-29
        • 2019-07-11
        • 2021-08-24
        • 2020-05-19
        • 2021-05-20
        • 2016-10-15
        相关资源
        最近更新 更多