This is regarding a question that I have just asked here : React expose component function
So when using componentDidMount on the 2 components where the functions are exposed, it looks like the componentDidMount for the data function takes some time to load, and then this causes returning an empty array. I am pretty new to react so I am not sure if this is the right way to use them.
class Data extends React.Component {
constructor() {
super();
this.state = {
names: []
}
}
componentDidMount() {
$.get('data.json', function (result) {
this.setState({
names: result.names
});
}.bind(this));
}
getNames(){
return this.state.names;
}
render(){
return (<div></div>);
}
}
class Layout extends React.Component {
constructor(){
super();
this.state = {
test: []
};
}
componentDidMount() {
this.state.test = this.refs.hello.getNames();
console.log(this.refs.hello.getNames());
}
something(){
console.log(this.state.test);
}
render(){
return(
<div>
<Data ref='hello' />
{this.something()}
</div>
)
}
}
const app = document.getElementById('app');
ReactDOM.render(<Layout />, app);
You have done a mistake of assigning value to a state in the layout component like this.state.test = this.refs.hello.getNames();, where you should be using setState(); Also it better to retrieve the data in the Layout component and if you want to use the data in Data component too then you can pass it as a prop to the same like
class Data extends React.Component {
constructor() {
super();
}
render(){
console.log(this.props.names)
return (<div></div>);
}
}
class Layout extends React.Component {
constructor(){
super();
this.state = {
test: []
};
}
componentDidMount() {
$.get('data.json', function (result) {
this.setState({
test: result.names
});
}.bind(this));
}
something(){
console.log(this.state.test);
}
render(){
return(
<div>
<Data ref='hello' names={this.state.test}/>
{this.something()}
</div>
)
}
}
const app = document.getElementById('app');
ReactDOM.render(<Layout />, app);
The problem here is that you are fetching in componentDidMount, you should be fetching in componentWillMount, that way you have the data before the component is rendered
Per the docs:
componentWillMount()is invoked immediately before mounting occurs. It is called beforerender(), (therefore settingstatein this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.)
All you need to do is change componentDidMount to componentWillMount
https://facebook.github.io/react/docs/react-component.html#componentwillmount