首页 > 解决方案 > 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: 

有什么想法可以为我指明正确的方向吗?非常感激!

标签: reactjsreact-propsreact-lifecycle

解决方案


有关答案,请查看@azium 的评论:

不,它不应该精确地显示在控制台中,因为componentDidMount它只在组件安装时运行一次。当Members组件调用setState并将新道具传递给 时Menu,它已经挂载,因此该函数和您的控制台日志将不会被填充的数组再次调用。您可以通过将控制台日志移动到render函数中来轻松测试
该组件创建之前接收道具,但道具是一个空数组。您在Members构造函数中明确说明了这一点。然后在Members安装后调用setState它会触发另一个带有填充数组的渲染。阅读文档以获得完整的解释/


推荐阅读