react-router的withRouter方法是干嘛的,什么时候要用到?

慕娘7196486
浏览 11673回答 1
1回答

Jokcy

首先withRouter可以用来给组件注入router相关的一些参数,比如:```import React from 'react'import PropTypes from 'prop-types'import { withRouter } from 'react-router'// A simple component that shows the pathname of the current locationclass ShowTheLocation extends React.Component { static propTypes = {    match: PropTypes.object.isRequired,    location: PropTypes.object.isRequired,    history: PropTypes.object.isRequired  }  render() {    const { match, location, history } = this.props    return (      <div>You are now at {location.pathname}</div>    )  }}// Create a new component that is "connected" (to borrow redux// terminology) to the router.const ShowTheLocationWithRouter = withRouter(ShowTheLocation)```其次withRouter是专门用来处理数据更新问题的。在使用一些redux的的`connect()`或者mobx的`inject()`的组件中,如果依赖于路由的更新要重新渲染,会出现路由更新了但是组件没有重新渲染的情况。这是因为redux和mobx的这些连接方法会修改组件的`shouldComponentUpdate`。座椅在使用withRouter解决更新问题的时候,一定要保证withRouter在最外层,比如`withRouter(connect(Component))`
打开App,查看更多内容
随时随地看视频慕课网APP