国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

javascript - react router 匹配路由組件后如何在組件中 dispatch action 一次?

瀏覽:162日期:2023-04-30 10:38:46

問題描述

用到了 react, react-router 4.1.1, redux 3.7.0, react-redux 5.0.5

Route配置為 <Route path='/:id' component={ Datagrid }/>,其中 id 為 path 路徑,Datagrid 為一個(gè)展示數(shù)據(jù)表格的容器組件,主體內(nèi)容為antd的 Table 組件,其中 columns 和 dataSource 要求能根據(jù) path 切換,我想實(shí)現(xiàn)當(dāng)點(diǎn)擊 /user 時(shí)加載 user 的 columns 和 dataSource,當(dāng)點(diǎn)擊/odm 時(shí)加載 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)點(diǎn)擊 /user path 時(shí)確實(shí)可以加載 user 的 column,但是dispatch(fetchColumn(id))會(huì)無限循環(huán),如果把dispatch(fetchColumn(id))放在componentDidMount中,只會(huì)加載一次,當(dāng)點(diǎn)擊 /odm 時(shí) Datagrid 組件又不會(huì)重新渲染了,不知道該怎么搞。

問題解答

回答1:

class Datagrid extends Component { //用于第一次掛載時(shí)請(qǐng)求 componentDidMount() { let id = this.props.match.params.id console.log(id) this.props.dispatch(fetchColumn(id)) } //當(dāng)props發(fā)生改變時(shí)請(qǐng)求 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)點(diǎn)擊/odm 時(shí)加載 odm 的 columns 和 dataSource。

那就在點(diǎn)擊事件里 dispatch 唄。

說錯(cuò)了,試試 componentDidUpdate。

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 浮山县| 收藏| 灯塔市| 浑源县| 肥乡县| 青河县| 丰都县| 沙田区| 汶川县| 类乌齐县| 宁晋县| 龙门县| 利辛县| 普安县| 墨竹工卡县| 厦门市| 视频| 星座| 长春市| 桐柏县| 杂多县| 常德市| 安化县| 乐至县| 邢台县| 徐水县| 新闻| 西峡县| 乌拉特后旗| 武穴市| 黔西| 华池县| 资讯 | 手游| 玉环县| 霍山县| 马公市| 昭平县| 兴化市| 平湖市| 石棉县|