gpt4 book ai didi

reactjs - react JS : Pass A value from route to component

转载 作者:行者123 更新时间:2023-12-04 01:12:33 24 4
gpt4 key购买 nike

我有这些路线

<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)

我需要从 ActiveReportsPage 访问 VALUE 以调用 API。我需要将从 URL 获取的值传递给 Axios API 调用,我该怎么做?

这是我的 ActiveReportsPage,如您所见

this.props.getReports(3); Calls the API and instead of 3 I should pass the 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);

最佳答案

您可以通过 Router 传递 params,可以通过 match prop 访问:

<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

关于reactjs - react JS : Pass A value from route to component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64377972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com