2016-12-20 16 views
1

http://codepen.io/anon/pen/KNEzOX?editors=0010调用另一个组件在react.js呈现

我有一个组件,它的获取和呈现的清单。我有组件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

第一关:

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

取永远不会在这里执行,因为回报。把回报放在最后。

其次,您需要的是在组件接收新道具时获取。我会做的是添加一个新的方法,将获取的类,并从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不会被调用。它只需要更新自己。

+0

我得到了你的第一点,修正了这一点。但我不明白你的第二个。我不知道如何从输入组件调用配置文件组件。 –

+0

我添加了一些代码来解释。 – Scimonster

+0

我认为我的结构是错误的。我不应该在组件A中进行提取,只是在点击处理程序中进行提取,然后将结果作为通道传递给将执行渲染的组件B. –

相关问题