React-router匹配params和forward按钮

问题描述 投票:1回答:1

我使用react-router有以下代码。

componentDidMount() {
    const { categories, isFetching, filterCategories, match } = this.props
    if (categories.length === 0 && !isFetching) {
        this.props.fetchData("categories", requestCategories, receiveCategories)
    }        

    window.onpopstate = ()=> {            
        filterCategories(match.params.category || "")
    }
}

期望match.params.category将始终根据URL中的内容返回类别

实际发生的情况通常很正常但是当我按下前进按钮时,match.params.category返回前一个URL的值。 enter image description here

我在这里做错了还是这个错误?

reactjs react-redux
1个回答
0
投票

我使用matchPath和'location.history'来解决这个问题。这让我可以解决matcha在按下后退或前进按钮时显示错误网址的事实。

import { matchPath } from 'react-router'
class CategoryContainer extends Component {


getCategoryFromUrl = (url) => {
    const match = matchPath(url, {path: '/:category', exact: true, strict: false})
    return match === null ? "" : match.params.category
}

/**
* @description - trigger a request action
*/
componentDidMount() {
    const { categories, isFetching, filterCategories, match, history } = this.props
    if (categories.length === 0 && !isFetching) {
        this.props.fetchData("categories", requestCategories, receiveCategories)
    }

    filterCategories(match.params.category || "")

    window.onpopstate = () => {
        filterCategories(this.getCategoryFromUrl(history.location.pathname))
        }

}
© www.soinside.com 2019 - 2024. All rights reserved.