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 为一个展示数据表格的容器组件,主体内容为antd的 Table 组件,其中 columns 和 dataSource 要求能根据 path 切换,我想实现当点击 /user 时加载 user 的 columns 和 dataSource,当点击/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))
当点击 /user path 时确实可以加载 user 的 column,但是dispatch(fetchColumn(id))会无限循环,如果把dispatch(fetchColumn(id))放在componentDidMount中,只会加载一次,当点击 /odm 时 Datagrid 组件又不会重新渲染了,不知道该怎么搞。
问题解答
回答1:class Datagrid extends Component { //用于第一次挂载时请求 componentDidMount() { let id = this.props.match.params.id console.log(id) this.props.dispatch(fetchColumn(id)) } //当props发生改变时请求 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:
当点击/odm 时加载 odm 的 columns 和 dataSource。
那就在点击事件里 dispatch 呗。
说错了,试试 componentDidUpdate。
相关文章:
1. objective-c - iOS怎么实现像QQ或者微信的实时推送2. 网页爬虫 - python爬虫翻页问题,请问各位大神我这段代码怎样翻页,还有价格要登陆后才能看到,应该怎么解决3. 求大神帮我看看是哪里写错了 感谢细心解答4. MySQL客户端吃掉了SQL注解?5. 数据库 - MySQL 单表500W+数据,查询超时,如何优化呢?6. php自学从哪里开始?7. mysql - AttributeError: ’module’ object has no attribute ’MatchType’8. android - Windows系统下运行react-native App时,报下面的错误?9. phpstady在win10上运行10. javascript - 图片能在网站显示,但控制台仍旧报错403 (Forbidden)
