javascript - react router 匹配路由組件后如何在組件中 dispatch action 一次?
問題描述
用到了 react, react-router 4.1.1, redux 3.7.0, react-redux 5.0.5
Route配置為 <Route path='/:id' component={ Datagrid }/>,其中 id 為 path 路徑,Datagrid 為一個展示數(shù)據(jù)表格的容器組件,主體內(nèi)容為antd的 Table 組件,其中 columns 和 dataSource 要求能根據(jù) path 切換,我想實現(xiàn)當(dāng)點擊 /user 時加載 user 的 columns 和 dataSource,當(dāng)點擊/odm 時加載 odm 的 columns 和 dataSource。
Datagrid 組件如下
import React, { Component } from ’react’import { Table, Button } from ’antd’import ’./index.less’import { fetchColumn } from ’../../actions/column’import { connect } from ’react-redux’import { withRouter } from ’react-router-dom’class Datagrid extends Component { render() { let id = this.props.match.params.id console.log(id) this.props.dispatch(fetchColumn(id)) return ( <p><Table columns={this.props.column}/> </p> ) }}const mapStateToProps = (state) => { return state}export default withRouter(connect(mapStateToProps)(Datagrid))
當(dāng)點擊 /user path 時確實可以加載 user 的 column,但是dispatch(fetchColumn(id))會無限循環(huán),如果把dispatch(fetchColumn(id))放在componentDidMount中,只會加載一次,當(dāng)點擊 /odm 時 Datagrid 組件又不會重新渲染了,不知道該怎么搞。
問題解答
回答1:class Datagrid extends Component { //用于第一次掛載時請求 componentDidMount() { let id = this.props.match.params.id console.log(id) this.props.dispatch(fetchColumn(id)) } //當(dāng)props發(fā)生改變時請求 componentWillReceiveProps(nextProps) { let id = this.props.match.params.id console.log(id) if(this.props.match.params.id != nextProps.match.params.id) {this.props.dispatch(fetchColumn(nextProps.match.params.id)) } } render() { return ( <p><Table columns={this.props.column}/> </p> ) }}回答2:
當(dāng)點擊/odm 時加載 odm 的 columns 和 dataSource。
那就在點擊事件里 dispatch 唄。
說錯了,試試 componentDidUpdate。
相關(guān)文章:
1. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?2. linux運維 - python遠程控制windows如何實現(xiàn)3. javascript - 從mysql獲取json數(shù)據(jù),前端怎么處理轉(zhuǎn)換解析json類型4. django - Python error: [Errno 99] Cannot assign requested address5. android - 安卓做前端,PHP做后臺服務(wù)器 有什么需要注意的?6. python小白 關(guān)于類里面的方法獲取變量失敗的問題7. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?8. thinkPHP5中獲取數(shù)據(jù)庫數(shù)據(jù)后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙9. extra沒有加載出來10. python - Scrapy如何得到原始的start_url
