[英]Why child component didnt get parent's props with Axios in React
loaded:false
loaded:false
I update the loaded
value to true, when i get the data, like so: 当我获取数据时,将
loaded
值更新为true,如下所示:
helpers.getValues().then(results => this.setState({values:results.data,loaded:true}));
And finally, inside the render()
i first check if the loaded==true
and then i render the ChildComponent, like so : 最后,在
render()
我首先检查是否loaded==true
,然后渲染ChildComponent,如下所示 :
{this.state.loaded == true ? <ChildComponent values={this.state.values} name="theodore"/> : ''}
I am making a simple code in React that gets data with Axios . 我在React中编写了一个简单的代码, 可以通过Axios 获取数据。
The data are returned to the client , so the communication is OK. 数据返回给客户端,因此通信正常。 The problem is that I pass the results data to a child component , as props, and as soon as the child component loads it asks for the props.data but it is empty.
问题是我将结果数据作为prop传递给子组件,并且一旦子组件加载,它就会要求props.data但它为空。
componentDidMount
I call the axios to get the data and update the setState
object. componentDidMount
内部,我调用axios来获取数据并更新setState
对象。 Below, into the render
function, I pass the results to the ChildComponent
. 下面,将结果传递给
ChildComponent
到render
函数中。
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> ) }
Inside the componentDidMount I try to show the props but the object that gets it like: {values:'',test:'ok'} 在componentDidMount内部,我尝试显示道具,但获得道具的对象如下: {values:'',test:'ok'}
var ChildComponent = React.createClass({
componentDidMount:function(){
console.log(this.props);
},
render:function(){
return(
<div>
<ul>'nothing'</ul>
</div>
)
}
});
I guess that it is a delay issue, in which the chld component loads before the axios async returns the data from server 我猜这是一个延迟问题,其中chld组件在axios异步从服务器返回数据之前加载
Any help from someone that has dealt with a similar situation would be appriciated, thanks. 谢谢处理类似情况的人的任何帮助。
Because you're passing this.state.movies
, instead of this.state.values
to the ChildComponent
. 因为您要将
this.state.movies
而不是this.state.values
传递给ChildComponent
。
How you do it : 你是如何做到的 :
<ChildComponent1 values={this.state.movies} test="ok"/>
How it should be : 应该如何 :
<ChildComponent1 values={this.state.values} test="ok"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.