React应用程序组件DidMount没有从父母那里获得道具

Die*_*nho 6 reactjs react-lifecycle react-props

我正在尝试将道具从父组件传递到子组件,即使它被调用了两次(不知道为什么,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;
Run Code Online (Sandbox Code Playgroud)

子组件:

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;
Run Code Online (Sandbox Code Playgroud)

来自Menu组件内componentDidMount的控制台日志打印:

interestList: 
interestList: 
Run Code Online (Sandbox Code Playgroud)

有什么想法可以指出正确的方向吗?不胜感激!

Die*_*nho 1

答案请看 @azium 的评论:

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