【发布时间】:2025-11-28 09:35:01
【问题描述】:
我在更新标头类时遇到了麻烦,因此每当调用 displaySection() 时它都会更新它的 className。我知道父状态发生了变化,因为在 displaySection() 中完成的控制台日志注册了 this.state.headerVisible 更改,但我的子组件中没有任何更改,我不知道我错过了什么,我一直在尝试不同几个小时的解决方案,我只是无法弄清楚我做错了什么,标题 headerVisible 值保持为 TRUE 而不是在状态更改时更改。
我在控制台中没有收到任何错误代码,只是子 Header 中的 prop headerVisible 没有在其父状态更改时得到更新。
谢谢!
class IndexPage extends React.Component {
constructor(props) {
super(props)
this.state = {
section: "",
headerVisible: true,
}
this.displaySection = this.displaySection.bind(this)
}
displaySection(sectionSelected) {
this.setState({ section: sectionSelected }, () => {
this.sectionRef.current.changeSection(this.state.section)
})
setTimeout(() => {
this.setState({
headerVisible: !this.state.headerVisible,
})
}, 325)
setTimeout(()=>{
console.log('this.state', this.state)
},500)
}
render() {
return (
<Layout>
<Header selectSection={this.displaySection} headerVisible={this.state.headerVisible} />
</Layout>
)
}
}
const Header = props => (
<header className={props.headerVisible ? 'visible' : 'invisible'}>
<div className="navbar-item column is-size-7-mobile is-size-5-tablet is-uppercase has-text-weight-semibold">
<span onClick={() => { this.props.selectSection("projects")}}>
{" "}
Projects
</span>
</header>
)
【问题讨论】:
-
你如何验证类名没有改变? FWIW,如果您根据现有状态计算状态,请始终将函数传递给
setState:this.setState(state =>({headerVisible: !state.headerVisible}))。 -
使用 Chrome 的 React 开发者工具,我可以看到 props 和 states 的变化。我看到 IndexPage 的状态发生了变化,但是 Header props 没有变化。
-
你能提供一个minimal reproducible example吗?
-
你永远不会调用 selectSection 函数。在返回页面内容之前为什么不尝试调用呢?
-
是的,没错,试图简化问题的代码,但我忽略了它,我的错
标签: javascript reactjs