React 应用程序 componentDidMount 未从父级获取道具

2024-01-28

我试图将道具从父组件传递到子组件,即使它被调用两次(不知道为什么,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: 

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


答案请查看@azium 的评论:

不,它不应该显示在控制台中,因为componentDidMount仅在组件安装时运行一次。什么时候Members组件调用setState并将新的 props 传递给Menu,它已经安装,因此不会使用填充的数组再次调用函数和控制台日志。您可以通过将控制台日志移至render功能
组件is在创建之前接收 props,但 prop 是一个空数组。你明确地说,在你的Members构造函数。然后Members你召唤的坐骑setState哪个触发another使用填充的数组进行渲染。阅读文档 https://reactjs.org/docs/state-and-lifecycle.html完整的解释/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 应用程序 componentDidMount 未从父级获取道具 的相关文章

随机推荐