react 父子组件执行顺序错误

在父子组件中都有componentDidMount周期函数,但发现每次都是父组件的componentDidMount先执行,之后在执行子组件的各个周期函数。这跟react所说的生命周期完全相反。这是为什么?

阅读 5.5k
3 个回答

Text 组件在TestPanel组件的 render 中,当 TestPanel 调用 render 时 Text的所有生命周期都会重新来一遍,包括 constructor 方法。

我怀疑你说的是 class Text extends TestPanel的这种形式.

你的子组件的mount可能是根据一些逻辑处理之后再执行的,这个时候父组件已经mount了

class Test extends Component{
    componentWillMount(){
        console.log('子组件将要挂载')
    }
    render(){
        return(<p>{this.props.index}</p>)
    }
}

export default class TestPanel extends Component{
    componentDidMount(){
        console.log('父组件挂载完毕');
    }
    render(){
        return(
            <div>
                <Test index={1}/>
                <Test index={2}/>
                <Test index={3}/>
            </div>
        )
    }
}

根据你的描述,我自己写了个小demo,顺序是正确的,父组件引入了子组件,子组件先执行,最后父组件执行,即是如下:

3*子组件将要挂载
父组件挂载完毕

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题