我正在尝试将道具从父组件传递给子组件,即使它被调用了两次(不知道为什么,componentDidMount
应该只被调用一次),道具似乎是空的。
父组件:
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;
从组件Didmount Inside Menu组件打印控制台日志:
interestList:
interestList:
有什么好主意给我指路吗? 非常感谢!
有关答案,请查看@azium的评论:
不,它不应该精确地显示在控制台中,因为componentDidMount
在组件挂载时只运行一次。当Members
组件调用setState
并将新的道具传递给Menu
时,它已经挂载,因此函数和控制台日志不会使用填充的数组再次调用。您可以通过将控制台日志移到render
函数中来轻松测试
组件在创建前正在接收道具,但道具为空数组。您可以在Members
构造函数中明确说明这一点。然后在Members
装载之后调用setState
,这将触发另一个使用填充的数组呈现。Read the docs了解详细说明/