React this.props.history.push 链接变了页面没变

阅读 (1522)
这是一个巨坑,不知道是因为用的React某些组件版本变了还是怎么回事,新起手的React项目最基础的功能this.props.history.push方法来进行路由跳转都无法生效,页面链接是变了,但页面没变,查了很久,最后居然是加载顺序问题
"antd-mobile": "^2.3.1",
"axios": "^0.19.2",
"qs": "^6.9.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-redux": "^7.2.0",
"react-router-dom": "^4.3.1",
"redux": "^4.0.5"

1.普遍情况:this.props 中未找到history

这种情况比较简单,

import { withRouter } from 'react-router-dom';

 导出时包裹一下组件即可

export default withRouter(PageNav)

如果是子组件,也可以由父组件传递history

例:父组件加载PageNav子组件时,加上props

<PageNav {...this.props}/>

2.少数情况是由于路由多嵌套了一层

import { BrowserRouter as Router } from 'react-router-dom'

这时的Router 整个项目全局只能用一层,不能嵌套,这种一般仔细看文档就不太会出现

 3.应该是极少数情况了

这也是我遇到的情况

项目初始的时候,我就从以前写的另一个项目复制了一些代码过来,包括redux

render () {
    let token = this.props.auth.token
    return (
      <Fragment>
        <Layout className={['layout', this.state.layoutClassName ? 'page' + this.state.layoutClassName : null].join(' ')}>
          <Content className="main-content">
            <div className="main-content-inner">
              <Switch>
                <Redirect from='/' exact to={{pathname: '/home'}} />
                {
                  Routers.map((item, index) => {
                    return (
                      <Route key={index} path={item.path} exact render={props =>
                        (!item.auth ? (<item.component {...props} />) : (token ? <item.component {...props} /> : <Redirect to={{
                        pathname: '/login',
                        state: { from: props.location }
                        }} />)
                      )} />
                    )
                  })
                }
                <Route component={NotFound} />
              </Switch>
            </div>
          </Content>
          <PageNav/>
        </Layout>

        <BackTop>
            <div className="ant-back-top-inner"><Icon type="arrow-up" /></div>
        </BackTop>
      </Fragment>
    )
  }
}

// 上面代码不重要
// 重点在下面。。。
const mapStateToProps = (state, ownProps) => {
  return { auth: state.auth }
}

export default connect(mapStateToProps)(withRouter(Main))

写法1:

export default connect(mapStateToProps)(withRouter(Main))

可是这个写法在我之前的项目中一点问题也没有。。。

写法2:

export default connect(mapStateToProps)(withRouter(Main))

原因:

connect内是进行shallow comparison浅比较的。它重写了组件的shouldComponentUpdate方法

写法1中,connect重写了withRouter的shouldComponentUpdate方法,导致其不能够响应location的变化(仅仅响应mapStateToProps里面的变化)

写法2中,将withRouter提到外层,withRouter的shouldComponentUpdate不会被重写,就会响应location的变化

这是我遇到的比较坑的地方,由于之前用了没问题,所以怎么也没往这方面想,会不会由于Redux相关的代码引起的,也怪自己没注意,不够仔细

更新于:2020-02-24 20:43:45
返回顶部