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

标签 reactjs react-props react-lifecycle

我试图将 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/

相关文章:

reactjs - 为什么console.log 在react js 中记录两次?

javascript - react : State not rendering in real time

reactjs - React hooks,从 prop 声明多个状态值

reactjs - 组件安装后,React 状态重置回初始值

javascript - ag-Grid 中的 cellRenderer 函数可以返回 React 组件吗?

javascript - 无法在Reactjs中加载js文件

reactjs - 在 React 应用程序中用 useContext 替换 props

reactjs - 如何在React 18中使用props.img

javascript - React 功能组件 useEffect 钩子(Hook)在类组件生命周期中具有相等的依赖性