javascript - 如何在异步更新时将 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}/>
)
})()}
解决方案
这个答案可能比您要求的要多,但在这里:
在此示例中,您具有三种状态:burgerClicked
(in Navbar.js
)、open
(in App.js
) 和showSideNav
(in header.js
)。
看起来这三个人都在跟踪同一件事:“侧导航是否打开?”。你不希望这样,你应该只有一个组件来跟踪它。
根据您的示例,我会说只App.js
应该具有该状态,并将其值传递给Navbar
并header
作为道具。
在Navbar.js
中,onClick
只需要调用clicked
函数,不传递任何参数。然后,App.js
确定是否设置open
为true
, false
(这很可能只是意味着切换它)。
一旦App.js
更新了它的状态,它将把更新后的值传递给header
and Navbar
,这就是 React 的美妙之处。
推荐阅读
- jquery - 每次函数运行时,如何将文本从一个 div 移动到另一个?
- symfony-2.3 - Swiftmailer 电子邮件问题
- maven - maven依赖快照版本号与nexus快照版本号相差1秒
- python - ValueError:使用高斯分布函数进行归一化期间的比例 < 0
- javascript - 使用 fs 为 discord.js 制作灵活的文件路径阅读器?
- javascript - 生成用于渲染外部组件的 JSX
- javascript - 通过容器 div Id 获取 ag-grid 实例
- python - Pandas - 通过在另一个数据框中查找来替换值
- python-3.x - Azure:使用 GraphRbacManagementClient 和 ServicePrincipalCredentials 结果导致权限不足错误
- python-3.x - 在 Python 3 中加载 mnist 数据集时出错