猿问

状态改变后条件渲染不改变

我是 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>

      }

我没有看到任何错误消息和状态正在更改的控制台日志。我不知道为什么会这样?


墨色风雨
浏览 123回答 2
2回答

料青山看我应如是

可能的错误在这里:&nbsp; <Switch>&nbsp; &nbsp; &nbsp; <Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.FileViewable}/>}/>&nbsp; </Switch>应该:<Switch>&nbsp; &nbsp; <Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.state.FileViewable}/>}/></Switch>(fileviewableState={this.FileViewable}应该是fileviewableState={this.state.FileViewable}

白衣非少年

尝试改变:如果(!this.props.fileviewableState)至:if(!this.state.FileViewable)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答