【问题标题】:call another component to render in react.js在 react.js 中调用另一个组件进行渲染
【发布时间】:2017-05-05 18:00:01
【问题描述】:

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>
        )
    }
});

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    首先:

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

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

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

    【讨论】:

    • 我明白了你的第一点,解决了。但我不明白你的第二个。我不知道如何从输入组件中调用配置文件组件。
    • 我认为我的结构是错误的。我不应该在组件 A 中进行 fetch,只需在 click 处理程序中进行 fetch,然后将结果作为 prop 传递给将进行渲染的组件 B。
    • 这是另一种方法。
    猜你喜欢
    • 2017-08-20
    • 2021-12-04
    • 2015-06-01
    • 2018-01-26
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多