【问题标题】:React Router + Redux + Transition group doesn't trigger special lifecycle hooksReact Router + Redux + Transition 组不会触发特殊的生命周期钩子
【发布时间】:2016-01-03 21:52:23
【问题描述】:

我正在使用 React Router + Redux,当我尝试加载嵌套视图(嵌套视图位于 ReactTransitionGroup 内)时,它会正确加载,但不会触发任何特殊钩子,例如 'ComponentWillEnter' 或 'ComponentWillLeave '。

在添加 Redux 'connects' 之前,它工作正常。

我的路线是这样的

<Route path="lists" component={Lists}>
        <Route path="listsA" component={ListsA}/>
        <Route path="listsB" component={ListsB}/>
 </Route>

我的组件

列表

@connect(..)
class Lists extends React.Component {
     ...
     render(){
        const { pathname } = this.props.location;
        const key = pathname.split('/') || 'Lists';
        const element = this.props.children || <div/>;
        const messages = this.props.messages;
        const elementToAnimate = React.cloneElement(element, { key, messages });

        return <div className="lists-wrapper">
            <div className="nested-views">
                <ReactTransitionGroup>
                    {elementToAnimate}
                </ReactTransitionGroup>
            </div>
        </div>
     }
}

列表A/列表B

@connect(..)
    class ListsA extends React.Component {
         ...
         render(){
            ...
          }
    }

我没有写太多代码,因为我不确定问题出在哪里,如果您需要我添加更多代码,我完全会的。

【问题讨论】:

    标签: reactjs react-router redux


    【解决方案1】:

    所以我昨晚也遇到了这个问题,这就是我发现的让它起作用的方法。

    首先有这种方法https://github.com/reactjs/react-redux/issues/101 您可以在其中使用处理特殊生命周期函数并将道具传递给您的连接组件的包装器来包装您的连接组件。

    或者

    您可以传递“withRef”标志来连接并从连接组件调用这些生命周期函数,然后让该函数调用您的组件生命周期函数。 我把它打包成一个包,你可以把它放在 connect 前面。

    // npm install --save connect-with-transition-group
    // https://github.com/esayemm/connect-with-transition-group
    
    import React, { Component, PropTypes } from 'react';
    import { connect } from 'react-redux'
    import connectWithTransitionGroup from 'connect-with-transition-group';
    
    class Foo extends Component {
      // ...
    
      componentWillEnter(cb) {
        // this works!
        cb();
      }
    
      // ...
    }
    
    export default connectWithTransitionGroup(connect(
      mapStateToProps,
      null,
      null,
      // IMPORTANT: must pass this flag to react-redux/connect
      {
        withRef: true,
      }
    )(Foo));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多