使用react-redux连接和redux数据的组件生命周期顺序

时间:2018-06-07 07:52:20

标签: reactjs react-native redux react-redux

我们都知道constructor -> componentWillMount -> componentDidMount是执行的顺序。

现在,当redux发挥作用并尝试在组件生命周期中访问redux属性时。 连接将执行的顺序是什么,以便数据可用生命周期方法忽略并将数据更新为redux。可能性是

1. Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount

2. constructor -> Connect (DATA AVAILABLE) -> componentWillMount & componentDidMount

3. constructor -> componentWillMount -> Connect (DATA AVAILABLE) -> componentDidMount

4. constructor -> componentWillMount -> componentDidMount -> Connect (DATA AVAILABLE) 

订单一致依赖对已加载的数据是什么?

反应和反应原生

之间有什么不同

并且可以将redux属性定义为PropType中

2 个答案:

答案 0 :(得分:6)

connect是一个包装组件的HOC,因此组件生命周期方法在连接生命周期之后。为了简单理解,您可以将连接写成这样的

const connect = (mapStateToProps, mapDispatchToProps) => (Component) => {
    return class ReduxApp extends React.Component {
        // lifecycle of connect
        render() {
            return (
                 <Component {...mapStateToProps(state)} />
            )
        }
    }
}

现在每当你的状态更新时,connect都会浅显要比较要返回给Component的道具列表,如果有更新更新了props,之后组件生命周期方法就像prop一样运行了。

简而言之,最初的执行是

Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount

数据更新后

Connect (DATA AVAILABLE) -> componentWillReceiveProps/getDerivedStateFromProps -> componentWillUpdate -> render -> componentDidUpdate

答案 1 :(得分:1)

初始执行顺序为 -

连接(数据可用) - &gt;构造函数&amp; componentWillMount&amp;渲染&amp; componentDidMount

当站点启动时,redux connect将在组件装载生命周期之前首先使用其默认状态和操作进行初始化。但是,如果redux中存在API调用,则组件装载生命周期不会等待数据。如果组件已经安装且redux返回数据,则将调用组件更新生命周期。

相关问题