基于状态变化的组件的条件渲染

时间:2018-06-08 20:41:46

标签: reactjs

当用户输入搜索项时,如果数据可用,则显示<Pictures />。如果数据不存在则显示<NoResultsFound />。默认<NoResultsFound />状态为false且<Pictures />为真,因为当页面加载时,图片列表存在。我试图像这样切换状态:this.setState({uisNoResultsFound: true}) and this.setState({uisPictures: false})抛出语法错误。我想在app.js中对UI状态进行这种条件渲染。怎么做?

App.js:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      uisSearchBarItems: true,
      uisNoResultsFound: false,
      uisPictures: true,
      dsPictures: []
    };
  }


  componentDidMount() {
    unsplash.search.collections("frog", 1, 60)
    .then(toJson)
    .then(json => {
      this.setState({ dsPictures:json.results });
    })
  }


  enteredDatahandler = (ctp) => {
    unsplash.search.collections(ctp, 1, 60)
    .then(toJson)
    .then(json => {
      this.setState({ dsPictures:json.results })
    })

    //******** conditional rendering ***********
    if(this.state.dsPictures.length === 0){
      return (
        this.setState({uisNoResultsFound: true})
        this.setState({uisPictures: false})
      )
    }
    else{
      this.setState({uisNoResultsFound: false})
      this.setState({uisPictures: true})    
    }
    //***********************************

  }




  render() {
    return (
      <div className="App">
        <SearchBarItems ctpEnteredData={this.enteredDatahandler}/>
        <NoResultsFound />
        <Pictures ptcEnteredData={this.state.dsPictures}/>
      </div>
    );
   }
  }

export default App;

searchbaritems.js

class SearchBarItems extends Component {

  enterKeyHandler = (event) => {
    if (event.key === 'Enter'){
        event.preventDefault(); 
        this.props.ctpEnteredData(this.search.value)
    }
  }


 render() {
    return (
        <div>
           <form autoComplete="off" ref={(el) => this.myFormRef = el}>
           <input 
          type="text" 
          name="search" 
          ref={input => this.search = input}
          onKeyPress={this.enterKeyHandler}/>
          </form>
       </div>  
    )
  }
}

2 个答案:

答案 0 :(得分:1)

在render方法中使用三元表达式。

{this.state.dsPictures.length === 0 ? <NoResultsFound /> :  <Pictures ptcEnteredData={this.state.dsPictures}/> }

答案 1 :(得分:1)

在渲染功能中,你要返回两个组件,你需要有if语句,或者你可以做@Barazu所做的 - 这是最干净的代码。

Github要点:https://gist.github.com/tintinmovie/ed5b4782fa98c3482b561ea3243f98ea

render() {
  if (this.state.uisNoResultsFound === true) {
    return(
      <div className="App">
        <SearchBarItems ctpEnteredData={this.enteredDatahandler}/>
        <NoResultsFound />
      </div>
    );
  }
  else if (this.state.uisPictures === true) {
    return(
      <div className="App">
        <SearchBarItems ctpEnteredData={this.enteredDatahandler}/>
        <Pictures ptcEnteredData={this.state.dsPictures}/>
      </div>
    );
  }
}
相关问题