反应应用程序组件Didmount没有从父母那里获得道具应用程序、道具、组件、反应

2023-09-03 12:39:35 作者:一世浮华乱谁浮生

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

从组件Didmount Inside Menu组件打印控制台日志:

interestList: 
interestList: 

有什么好主意给我指路吗? 非常感谢!

推荐答案

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

不,它不应该精确地显示在控制台中,因为componentDidMount在组件挂载时只运行一次。当Members组件调用setState并将新的道具传递给Menu时,它已经挂载,因此函数和控制台日志不会使用填充的数组再次调用。您可以通过将控制台日志移到render函数中来轻松测试 组件在创建前正在接收道具,但道具为空数组。您可以在Members构造函数中明确说明这一点。然后在Members装载之后调用setState,这将触发另一个使用填充的数组呈现。Read the docs了解详细说明/