调用另一个组件来在react.js中呈现

时间:2016-12-20 13:37:47

标签: javascript reactjs

http://codepen.io/anon/pen/KNEzOX?editors=0010

我有一个组件A来执行获取并呈现列表。我有组件B接受用户输入。如何从组件B中激活组件A?我想我的结构是错误的。

const Profiles = React.createClass({
  getInitialState(){
    return {profiles: []}
    if(!this.props.username){
      return false;
    }
    fetch('https://api.github.com/search/users?q=' + this.props.username)
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        this.setState({profile: json.items})
      })
  },
  render(){
    return (
      <ul>
        {
          this.state.profiles.map(profile => 
            <li key={profile.id}>profile.name</li>
          )
        }
      </ul>
    )
  }
})

const Input = React.createClass({
    getInitialState(){
      return {username:''}
    },
    handleInputChange(e){
      this.setState({username:e.target.value})
    },
    handleSearch(){
      if(!this.state.username){
        alert('username cannot be empty');
        return false;
      }
      //call profile component and pass username to it?
    },
    render() {
        return(
          <div>
            <input type="text" placeholder="github username" onChange={this.handleInputChange} value={this.state.username} />
            <button onClick={this.handleSearch}>Search</button>
            <Profiles username={this.state.username} />
          </div>
        )
    }
});

1 个答案:

答案 0 :(得分:1)

首先关闭:

getInitialState(){
    return {profiles: []}
    if(!this.props.username){
      return false;
    }
    fetch('https://api.github.com/search/users?q=' + this.props.username)

由于返回,Fetch永远不会在这里执行。把回报放在最后。

其次,你需要的是它在组件接收新道具时获取。我要做的是为要获取的类添加一个新方法,并从getInitialStatecomponentWillReceiveProps调用它。所以:

  getInitialState(){
    if(!this.props.username){
      return false;
    }
    this._fetchData();
    return {profiles: []}
  },
  componentWillReceiveProps(){
    this._fetchData();
  },
  _fetchData(){
    fetch('https://api.github.com/search/users?q=' + this.props.username)
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        this.setState({profile: json.items})
      })
  },

问题是组件已经存在,因此getInitialState不会被调用。它只需要更新自己。