【问题标题】:Redux state and useState not syncRedux 状态和 useState 不同步
【发布时间】:2021-05-30 13:25:54
【问题描述】:

我想将我的 reduxState 设置为 useState,但问题是 reduxState 在渲染后出现,然后 useState 仍然有 null ,这是在第一次渲染时得到的。 期望:reduxState 将每个更改或更新传递给 useState。

    const Account: React.FC<Props> = ({ logInAction, userDataStore }) => {
        const [userValues, setUserValues] = useState<User>(userDataStore as User);
        return (
         <Text>
             {/*
              this data (userValues) still null 
              despite userDataStore 
              is changed and has Data
             */}
          Fullname: {userValues.fullName}  
         </Text>
        );
        .
        .
        .
        export default connector(Account);

我知道直接使用 redux state 对我有用:

userDataStore.fullName
     <Text>
                   {/* fullName: {userValues.fullName} */} ---> not work always null
                   fullName: {userDataStore.fullName} ---> this work good

              </Text>
    );

但我想使用 useState。 有什么帮助吗?

我将不胜感激。

【问题讨论】:

    标签: reactjs react-native redux react-redux react-hooks


    【解决方案1】:

    不确定您不想使用 reduxState 并使用 useState 挂钩的原因是什么,但您可以通过添加 useEffect 挂钩来实现 reduxState 和用户值之间的同步:

        const [userValues, setUserValues] = useState<User>(userDataStore as User);
        useEffect(() => {
          setUserValues(userDataStore as User)
        }, [userDataStore]);
        ...
    

    这将在userDataStore 更改时设置userValues

    【讨论】:

    • 成功了 :D 谢谢一百万兄弟
    猜你喜欢
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2016-08-04
    • 2021-04-26
    • 2021-12-30
    • 2017-10-23
    • 2018-11-29
    相关资源
    最近更新 更多