I'm trying to pass props from a parent component to a child component and even though its getting called twice (dunno why, componentDidMount
should get called only once) the props seem to be empty.
Parent component:
class Members extends Component{
constructor(props){
super(props);
this.state = {
interests: []
}
}
componentDidMount(){
fetch(interestUrl, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Authorization": this.props.authToken
}
})
.then((response) => response.json())
.then((json) => {this.setState({interests: json})})
.catch(error => {console.log("Error: " + error)})
};
render(){
return(
<div className="Members-body">
<div className="Menu-sidebar">
<Menu interestList = {this.state.interests}/>
</div>
<div className="Main-container">
<Main/>
</div>
</div>
)
}
}
export default Members;
Child component:
class Menu extends Component {
constructor(props){
super(props);
}
componentDidMount(){
console.log("interestList: " + this.props.interestList);
}
render() {
return(
<div className="Menu-container">
este es el menu de la aplicacion
</div>
)
}
}
export default Menu;
The console log from componentDidMount inside Menu component prints:
interestList:
interestList:
Any ideas to point me in the right direction? Greatly appreciated!
Main
component isn't pointing toMenu
– Dior"foo: " + []
– BissellcomponentDidMount
so it should be called after the component rendered and should have the props passed by the parent – AeromedicalcomponentDidMount
only runs once, when the component mounts. whenMembers
component callssetState
and pass new props toMenu
, it has already mounted so that function and your console log won't be called again with the populated array. you can test this easily by moving your console log into therender
function – BissellMembers
constructor. Then afterMembers
mounts you callsetState
which triggers another render with the populated array. Read the docs for a full explanation/ – Bissell