【问题标题】:how can i set initial value for usestate from redux state using selector in react native?如何在 react native 中使用选择器从 redux 状态设置 usestate 的初始值?
【发布时间】:2022-01-14 09:52:04
【问题描述】:

当我尝试从 redux 状态设置初始值时,文本组件上没有任何内容,但我可以在控制台上看到该值

   const Profile = props => {

   const userName = useSelector(userSelector);
   const [name, setName] = useState(userName);
   
   console.log(userName);
   
       return (
           <Text>{name}</Text>

       );
}; 

【问题讨论】:

  • 你不需要使用useState直到你需要在本地改变它,因为使用选择器redux,当它改变时会自动更新。

标签: reactjs react-native react-redux use-state


【解决方案1】:

它不会这样工作,因为 redux 在初始渲染后获取它的值,所以你只需要在 redux 值更新后更新你的状态

如果你的 redux store 是一个字符串,你可以直接使用 userName 代替 name。

使用 useEffect 挂钩并将 userName 添加到其依赖项数组中。

useEffect(() => {
  setName(userName);
}, [userName])

在你的 react 组件中添加这个,它会起作用的!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2019-08-17
    • 2016-10-15
    • 2020-05-19
    • 2021-03-10
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多