为什么子组件在React

时间:2017-02-03 14:41:19

标签: javascript http reactjs asynchronous axios

我用一个简单的标志来解决它:

  1. 我在状态对象上添加了一个新的标记属性:loaded:false
  2. 当我获取数据时,我将loaded值更新为true,如下所示:

     helpers.getValues().then(results => this.setState({values:results.data,loaded:true}));
    
  3. 最后,在render()我首先检查是否loaded==true,然后我渲染ChildComponent,就像这样

    {this.state.loaded == true ? <ChildComponent values={this.state.values} name="theodore"/> : ''}
    
  4. 我在 React 中制作了一个简单的代码,获取数据 Axios

    数据返回给客户端,因此通信正常。 问题是我将结果数据作为道具传递给子组件,并且一旦子组件加载它就要求 props.data 但它是空的。

    以下是父组件:

    1. componentDidMount内部,我调用axios来获取数据并更新setState对象。
    2. 下面,在render函数中,我将结果传递给ChildComponent。 的

      var ParentComponent = React.createClass({
          getInitialState:function(){
              return {
                  values:''
                  activeTab:0
              }
          },
          componentDidMount:function(){
              helpers.getValues().then(results => this.setState({values:results.data}));
          },
          render:function(){
              return(
                  <div className='container'>
                      <div className="row">
                          <div className="col-sm-8 text-center" >
                              <h1>{pageTitle}</h1>
                              <Tabs activeKey={this.state.activeTab} onSelect={this.handleSelect} id="controlled-tab-example">
                                  <Tab eventKey={tabs[0].key} title={tabs[0].name}>
                                      Tab1
                                      <ChildComponent1 values={this.state.values} test="ok"/>
                                  </Tab>
                                  <Tab eventKey={tabs[1].key} title={tabs[1].name}>Tab2</Tab>
                              </Tabs>
                          </div>
                      </div>
                  </div>
              )
          }
      
    3. 这里我展示了ChildComponent(在一个单独的js文件中)。

      componentDidMount 中,我尝试显示道具但是获取它的对象: 的 {值: '',试验: 'OK'}

      var ChildComponent = React.createClass({
          componentDidMount:function(){
              console.log(this.props);
          },
          render:function(){
              return(
                  <div>
                      <ul>'nothing'</ul>
                  </div>
              )
          }
      });
      

      我想这是一个延迟问题,其中chld组件在axios异步从服务器返回数据之前加载

      处理类似情况的人的任何帮助都会受到关注,谢谢。

1 个答案:

答案 0 :(得分:0)

因为您将this.state.movies而不是this.state.values传递给ChildComponent

你是怎么做的

<ChildComponent1 values={this.state.movies} test="ok"/>

应该如何

<ChildComponent1 values={this.state.values} test="ok"/>