Umi: 在 layout 中使用 connect 将导致切换路由失效

Created on 22 Mar 2018  ·  3Comments  ·  Source: umijs/umi

// layouts/index.js
import withRouter from 'umi/withRouter';
import Link from 'umi/link';
import { connect } from 'dva';
// 如果在 layout 中使用 connect,点击 Link 切换路由时
// 路由能够正常切换,但是切换 props.children 失效(表现为还是停留在原有页面)
export default connect( state => ({}) )( 
    withRouter(
      function(props){
        return <div>
          <Link to="/">/</Link><br/>
          <Link to="/page1">/page1</Link><br/>
          <Link to="/page2">/page2</Link><br/>
          { props.children }<br/>
        </div>;
      }
    )
  );
type(question)

Most helpful comment

原因如下:
connect 进行的是 shallow comparison 浅比较。它重写了组件的 shouldComponentUpdate 方法。 如果 connect 放在前面,会重写 withRoutershouldComponentUpdate 方法,导致其不能够响应location的变化(仅仅响应mapStateToProps里面的变化)

All 3 comments

umi -v = 1.0.8

在 umi 反馈群内咨询了有同学说

之前听说是 先withRouter 再connect

在我这边可以解决遇到的问题

原因如下:
connect 进行的是 shallow comparison 浅比较。它重写了组件的 shouldComponentUpdate 方法。 如果 connect 放在前面,会重写 withRoutershouldComponentUpdate 方法,导致其不能够响应location的变化(仅仅响应mapStateToProps里面的变化)

Was this page helpful?
0 / 5 - 0 ratings