reactjs - 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);
解决方案
你可以params
通过Router,它可以通过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
推荐阅读
- vue.js - 如何使用 bot 构造函数提供的 http url 在 js 文件中的对象中包含 Nuxt 应用程序中的外部 html?
- ffmpeg - ffmpeg 使用 drawtext 和 subtitle 垂直居中对齐多行文本,这两个过滤器都与字体大小无关
- python - 用 re.IGNORECASE 替换多个子字符串
- parsing - 具有 GLR、优先级和非关联性的极端案例:预期语义?
- c - 如何从文本行获取特定数据
- javascript - 快速拨号图标未居中
- ios - 如何在从情节提要实例化的 UIButton 类中获取视图控制器的实例
- php - 将图像上传到 sql server 上的 varbinary 字段时,file_get_contents 值中的“附近语法不正确”
- java - 将新字段无缝添加到 JSON
- javascript - 为什么在asp.net核心中发送请求时axios响应骆驼情况