我是React的新手,我正在尝试在无状态子组件中执行条件渲染。当我更新状态以强制条件改变时,什么也没发生。
我已经检查以确保我的回调函数实际上正在更改其状态。我确保道具能够正常工作,因为我能够通过道具从孩子那里检索其他数据。
//main app component
this.state={
FileViewable: false
}
changeViewStatetoTrue = () =>{
this.setState({FileViewable:!this.state.FileViewable}, function (){
console.log(this.state.FileViewable)
});
//there are more routes but I just wanted to include the route in question
<Switch>
<Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.FileViewable}/>}/>
</Switch>
//Body component where the conditional rendering should happen, there is a Tesseract OCR API call being made here, i've left it out because it works fine
render(props) {
var documentView;
if(!this.props.fileviewableState){
documentView = <div> view number 1 </div>
} else {
documentView = <div>
<h1>view number 2 </h1>
</div>
}
我没有看到任何错误消息,并且控制台记录了状态正在更改。我不知道为什么会这样?
答案 0 :(得分:0)
可能的错误在这里:
<Switch>
<Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.FileViewable}/>}/>
</Switch>
应该是:
<Switch>
<Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.state.FileViewable}/>}/>
</Switch>
({fileviewableState={this.FileViewable}
应该是fileviewableState={this.state.FileViewable}
答案 1 :(得分:0)
尝试更改:
if(!this.props.fileviewableState)
收件人:
if(!this.state。FileViewable)