我试图将 Prop 从父组件传递到子组件,即使它被调用两次(不知道为什么,componentDidMount
应该只被调用一次), Prop 似乎是空的。
父组件:
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;
子组件:
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;
Menu 组件内的 componentDidMount 的控制台日志打印:
interestList:
interestList:
有什么想法可以指引我正确的方向吗? 非常感谢!
最佳答案
要获得答案,请查看@azium 的评论:
no it shouldn't show in the console precisely because
componentDidMount
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
The component is receiving the props before being created, but the prop is an empty array. You explicitly say that in yourMembers
constructor. Then afterMembers
mounts you callsetState
which triggers another render with the populated array. Read the docs for a full explanation/
关于reactjs - React 应用程序 componentDidMount 未从父级获取 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50094331/