gpt4 book ai didi

reactjs - React 应用程序 componentDidMount 未从父级获取 Prop

转载 作者:行者123 更新时间:2023-12-03 13:32:08 24 4
gpt4 key购买 nike

我试图将 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. when Members component calls setState and pass new props to Menu, 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 the render function
The component is receiving the props before being created, but the prop is an empty array. You explicitly say that in your Members constructor. Then after Members mounts you call setState 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com