如何通过异步函数设置父组件状态,然后将此状态作为道具传递给子组件?

时间:2018-09-23 10:33:32

标签: javascript reactjs async-await react-props react-lifecycle

所以我想通过firebase函数设置访问权限,然后将此访问道具作为props传递给tabs组件,但是tabs组件的初始状态为null,之后解决了firebase auth函数。

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}/>
  }
}

3 个答案:

答案 0 :(得分:1)

您可以执行conditional rendering并且只有在获得访问权限后才呈现选项卡:

return this.state.access 
    ? <Tab access={this.state.access}/> 
    : <div>Not authorized</div>

答案 1 :(得分:1)

应该没问题。更新状态时,组件将重新渲染,并且其所有子代也将重新渲染。如果在访问为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'}

答案 2 :(得分:1)

componentDidMount函数在渲染之后被调用,即使您在componentWillMount中进行了调用,由于该函数是异步调用,因此仅在触发组件渲染周期后才可以解析它,因此渲染后,数据将只有一个值。为了正确处理这种情况,您必须有条件地在渲染器中渲染数据。

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}/>
  }
}
相关问题