【发布时间】:2018-10-10 04:24:56
【问题描述】:
我正在尝试将道具从父组件传递给子组件,即使它被调用了两次(不知道为什么,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:
有什么想法可以为我指明正确的方向吗? 非常感谢!
【问题讨论】:
-
您确定菜单组件没有在您的 UI 中的两个位置加载。您还可以确保
Main组件没有指向Menu -
console.log 也是正确的。你可以在控制台中测试这个
"foo: " + [] -
不,它不应该准确地显示在控制台中,因为
componentDidMount仅在组件安装时运行一次。当Members组件调用setState并将新道具传递给Menu时,它已经挂载,因此该函数和您的控制台日志将不会被填充的数组再次调用。您可以通过将控制台日志移动到render函数来轻松测试这一点 -
组件正在在创建之前接收props,但是props是一个空数组。您在
Members构造函数中明确表示。然后在Members挂载后调用setState,它会触发another 使用填充的数组进行渲染。 Read the docs完整解释/
标签: reactjs react-props react-lifecycle