简体   繁体   English

如何在反应原生中使用选择器从 redux state 设置 usestate 的初始值?

[英]how can i set initial value for usestate from redux state using selector in react native?

when I try to set initial value from redux state, there is nothing on text component but i can see the value on console当我尝试从 redux state 设置初始值时,文本组件上没有任何内容,但我可以在控制台上看到该值

   const Profile = props => {

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

       );
}; 

It won't work this way, as redux is getting its value after the initial render so you need to update your state only after the redux value is updated它不会以这种方式工作,因为 redux 在初始渲染后获得其值,因此您需要仅在更新 redux 值后更新 state

Use an useEffect hook and add userName to its dependency array.使用 useEffect 钩子并将 userName 添加到其依赖项数组中。

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

Add this inside your react component and it will work!!将此添加到您的反应组件中,它将起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM