亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕娘7196486 2018-01-11 10:08:52
查看完整描述

1 回答

?
Jokcy

TA貢獻2條經驗 獲得超6個贊

首先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 location

class 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))`

查看完整回答
6 反對 回復 2018-01-12
  • 1 回答
  • 0 關注
  • 11715 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號