首页 > 解决方案 > 如何在异步更新时将 state 属性作为 prop 传递以显示和隐藏组件

问题描述

当我点击它时我有一个导航栏我将我的状态设置为true并将它作为道具传递到我的组件中但是该函数需要时间来更新它并且我的道具被发送为假我如何在状态更新时发送我更新的道具已经完成

导航栏.js

 constructor(props) {
    super(props);
    this.state = {
      burgerClicked:false,
    };
  }
 burgerClicked=()=>{
    this.setState({ burgerClicked: true },()=>{   this.props.clicked(this.state.burgerClicked)})
  }

应用程序.js

 constructor(props){
    super(props);
     this.state={
      open:false,
     }
  }

 openSideNav =(burgerClicked)=>{// the time is taking here to update it send open as false 
     this.setState({open:burgerClicked},()=>{
       console.log(this.state.open)
     });

 <Navbar clicked={this.openSideNav} tokenRequested={this.request}/>
 <Header  open={this.state.open} />

header.js

constructor(props) {
    super(props);
    this.state = { showSideNav: false };
  }


UNSAFE_componentWillReceiveProps(){
    // 
    console.log(this.props.open,this.state.showSideNav);//this.props.open is false

    if (this.props.open) {
      this.setState({showSideNav:this.props.open},()=>{
        console.log(this.state.showSideNav); //this.state.showSideNav dont print on first click but print true on second click on burger

      })
    }

    console.log(this.props.open,this.state.showSideNav); //this.props.open is false
  }

   {(() => {
  if (!this.state.showSideNav) {
         return null;
        }
          return(
          <SideNavbar closeNav={this.closeSideNav}/>
           )
   })()}

标签: javascriptreactjs

解决方案


这个答案可能比您要求的要多,但在这里:

在此示例中,您具有三种状态:burgerClicked(in Navbar.js)、open(in App.js) 和showSideNav(in header.js)。

看起来这三个人都在跟踪同一件事:“侧导航是否打开?”。你不希望这样,你应该只有一个组件来跟踪它。

根据您的示例,我会说只App.js应该具有该状态,并将其值传递给Navbarheader作为道具。

Navbar.js中,onClick只需要调用clicked函数,传递任何参数。然后,App.js确定是否设置opentrue, false(这很可能只是意味着切换它)。

一旦App.js更新了它的状态,它将把更新后的值传递给headerand Navbar,这就是 React 的美妙之处。


推荐阅读