[英]how to pass props to initial state in useState hook?
I am having an issue with initialising a useState hook with props that is passed to the current component from another.我在使用从另一个传递给当前组件的道具初始化 useState 挂钩时遇到问题。
the areas where I am having the issue is below (Keep in mind that I can access the prop if i just console.log it, so it not a matter of a failure of the prop passing data down)我遇到问题的区域如下(请记住,如果我只是 console.log 就可以访问道具,所以这不是道具传递数据失败的问题)
const [ Uid, setUid ] = useState('');
It is important for me to pass the props like below as my data fetching on this component depends on Uid.传递如下属性对我来说很重要,因为我在此组件上获取的数据取决于 Uid。 So far I have tried
到目前为止我已经尝试过
const [ Uid, setUid ] = useState(props.uid);
this did not work as it told me- first argument to be of type non-empty string, but it was: undefined这不起作用,因为它告诉我 - 第一个参数是非空字符串类型,但它是:未定义
const [ Uid, setUid ] = useState(props);
useEffect(() => {
setUid(props.uid);
}, []);
Can anyone see where i might be going wrong?谁能看到我可能出错的地方?
the full code is here- https://www.codepile.net/pile/m3zmwnK1完整代码在这里-https://www.codepile.net/pile/m3zmwnK1
remember, the most important thing for me is to have the Uid contain the value from the props.uid as otherwise react gives me a "first argument to be of type non-empty string, but it was: undefined" issue请记住,对我来说最重要的是让 Uid 包含来自 props.uid 的值,否则反应会给我一个“第一个参数类型为非空字符串,但它是:未定义”问题
You are ignoring props.uid in subsequent effects.您在后续效果中忽略了 props.uid。 Try this
尝试这个
const Component({uid}){
const [stateUid, setUid] = useState(uid);
useEffect(()=>{
setUid(uid);
},[uid])
}
You might want to add props to your useEffect
dependency.您可能希望将道具添加到您的
useEffect
依赖项。 If it changes too often, u might drop into infinite loop如果它变化太频繁,你可能会陷入无限循环
useEffect(() => {
setUid(props.uid);
}, [props.uid]);
In you App.js在你 App.js
function App() {
const [ user, setuser ] = useState(false);
const [ uid, setUid ] = useState(); //initial is empty
useEffect(() => {
const unsubscribe = onAuthStateChange();
return () => {
unsubscribe();
};
}, []); // it only run once so it might not set the state of uid
return <div className="App">{user ? <Home uid={uid} /> : <Form />}</div>;
// uid passing to Home component might be empty
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.