reactjs - React app componentDidMount没有从父级获取道具
问题描述
我试图将道具从父组件传递给子组件,即使它被调用了两次(不知道为什么,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;
来自 Menu 组件内的 componentDidMount 的控制台日志打印:
interestList:
interestList:
有什么想法可以为我指明正确的方向吗?非常感激!
解决方案
有关答案,请查看@azium 的评论:
不,它不应该精确地显示在控制台中,因为
componentDidMount
它只在组件安装时运行一次。当Members
组件调用setState
并将新道具传递给 时Menu
,它已经挂载,因此该函数和您的控制台日志将不会被填充的数组再次调用。您可以通过将控制台日志移动到render
函数中来轻松测试
该组件在创建之前接收道具,但道具是一个空数组。您在Members
构造函数中明确说明了这一点。然后在Members
安装后调用setState
它会触发另一个带有填充数组的渲染。阅读文档以获得完整的解释/
推荐阅读
- javascript - TypeError:无法读取 null 的属性(读取“addEventListener”)
- java - JNI 原生类方法获取错误的参数值
- python-3.x - 在大型嵌套字典中查找特定键
- laravel - [Route: storage_file][URL: files/{filename}] 缺少必需参数 [缺少参数:filename]
- javascript - Google Apps 脚本中的二维数组
- c# - 限制长的大小?
- javascript - Expo json意外的输入结束
- reactjs - 如何在 React 中显示灵活的网格
- amazon-web-services - 我在哪里可以找到 AWS CUR 中每个服务 lineItem/Operation 的列表?
- android - Android 共享元素转换无法按预期正常工作