[英]how to set react parent component state by a async function and then pass this state to child as props?
so i want to set the access by firebase function and then pass this access props to tabs component as props ,but tabs component is get the initial state null,firebase auth funtion is resolving after that . 所以我想通过firebase函数设置访问权限,然后将此访问道具传递给tabs组件作为props,但是tabs组件获取初始状态为null,firebase auth funtion在此之后解析。
class Admin extends React.Component {
state = {
access: null,
};
componentDidMount() {
this.unListen = firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState(() => ({ access: true }));
}
});
}
componentWillUnmount() {
this.unListen();
}
render(){
return <Tab access={this.state.access}/>
}
}
You can do conditional rendering and not render the tabs until you get access: 在获得访问权限之前,您可以执行条件渲染并且不渲染选项卡:
return this.state.access
? <Tab access={this.state.access}/>
: <div>Not authorized</div>
It should not be a problem. 这应该不是问题。 When you update the state, the component will re-render and all its children will also be re-rendered.
更新状态时,组件将重新呈现,并且还将重新呈现其所有子项。 If you don't want to render anything while access is null try the following code.
如果您不想在访问为null时呈现任何内容,请尝试以下代码。
class Admin extends React.Component {
state = {
access: null,
};
componentDidMount() {
this.unListen = firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState(() => ({ access: true }));
}
});
}
componentWillUnmount() {
this.unListen();
}
render(){
const access = {this.state};
return {access && <Tab access={access}/>}
}
}
OR 要么
{access ? <Tab access={access}/> : 'Not Authorized'}
componentDidMount
function is called after the render and even though you have your call in componentWillMount
, since its an async call, it will only be resolved after the component render cycle has been triggered and hence the data will only have a value after render. 在呈现之后调用
componentDidMount
函数,即使您在componentWillMount
调用,因为它是异步调用,它只会在触发组件呈现周期后解析,因此数据在呈现后只有一个值。 In order to correctly handle such a scenario, you must conditionally render your data in the render. 为了正确处理这种情况,您必须在渲染中有条件地渲染数据。
class Admin extends React.Component {
state = {
access: null,
};
componentDidMount() {
this.unListen = firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState(() => ({ access: true }));
}
});
}
componentWillUnmount() {
this.unListen();
}
render(){
const { access } = this.state;
if(access !== null) {
return null;
}
return <Tab access={this.state.access}/>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.