首页 > 解决方案 > React JS:将值从路由传递到组件

问题描述

我有这些路线

<Router>
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/reports" exact component={ReportPage} />
    <Route path="/reports/browse" exact component={ActiveReportsPage} />
    <Route path="/signin" exact component={SigninPage} />
  </Switch>
</Router>;

我想用这个 - /reports/browse/[ VALUE ] 例如 - (localhost:8000/reports/browse/1)

我需要访问 VALUEActiveReportsPage来调用 API。我需要将从 URL 获得的值传递给 Axios API 调用,我该怎么做?

这是我的ActiveReportsPage,如你所见

this.props.getReports(3);调用 API 而不是 3 我应该传递 VALUE

import React, {Component, useState} from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getReports } from '../actions/reports';

export class ActiveReportsPage extends Component {

    static PropTypes = {
        reports: PropTypes.array.isRequired
    }

    componentDidMount() {
        this.props.getReports(3); {/* I need to pass in the argument from /reports/browse/< 1,2,3,4,5,6,7,8,9,10 > */}
    }

    constructor(props) {
        super(props);
        this.state = {
            isOpen: false
        };
    }

    render() {
        return (
            <h2>hello :P</h2>
        )
    }
};

const mapStateToProps = state => ({
    reports: state.reports.reports
});

export default connect(mapStateToProps, { getReports })(ActiveReportsPage);

标签: reactjs

解决方案


你可以params通过Router,它可以通过matchprop访问:

<Router>
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/reports/:parameter" exact component={ReportPage} />
    <Route path="/reports/browse" exact component={ActiveReportsPage} />
    <Route path="/signin" exact component={SigninPage} />
  </Switch>
</Router>;

然后可以在 ReportsPage 组件中通过以下方式访问:this.props.match.params.parameter


推荐阅读