我在更新 header 类时遇到问题,因此每当调用 displaySection() 时它都会更新它的 className。我知道父状态发生了变化,因为在 displaySection() 中完成的控制台日志注册了 this.state.headerVisible 更改,但我的子组件中没有任何更改,我不知道我错过了什么,我一直在尝试不同的方法几个小时的解决方案,我只是无法弄清楚我做错了什么, header 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>
)
最佳答案
您的示例代码似乎存在一些问题:
- 标题中缺少结束 div
- 在 header 的 span 中的 onclick 中使用
this.props
代替props
下面的最小示例似乎可以工作。我必须删除您对 this.sectionRef.current.changeSection(this.state.section)
的调用,因为我不知道sectionRef 应该是什么,因为它不在您的示例中。
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 })
setTimeout(() => {
this.setState({
headerVisible: !this.state.headerVisible,
})
}, 325)
setTimeout(()=>{
console.log('this.state', this.state)
},500)
}
render() {
return (
<div>
<Header selectSection={this.displaySection} headerVisible={this.state.headerVisible} />
</div>
)
}
}
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={() => { props.selectSection("projects")}}>
{" "}
Projects
</span>
</div>
</header>
)
ReactDOM.render(
<IndexPage />,
document.getElementsByTagName('body')[0]
);
.visible {
opacity: 1
}
.invisible {
opacity: 0
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
关于javascript - react : Unable to update children props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55698602/