reactjs - 如何根据所选选项在 api url 中传递参数?
问题描述
我想根据选定的作业 ID 获取数据。应从下拉列表中选择作业 ID。选择作业 ID 后,应使用属性作业 ID 调整 api url。
我添加了 select 选项和 fetch 语句。但是我无法在 url 中传递参数。
const jsonify = res => res.json();
var chart_request = new Request(
`https://xxxx.com/prod/job-id?job_id_number=${this.state.selectVal}`,
{
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
}
);
const dataFetch = fetch(chart_request).then(jsonify);
export default class ZYZ extends Component {
constructor(props) {
super(props);
this.state = {
selectVal : "650"
}
}
setSelectValue = (event) => {
this.setState({
selectVal: event.target.value
});
}
render() {
return
<React.Fragment>
<select value={this.state.selectVal} onChange={this.setSelectValue}>
<option value = "650">650</option>
<option value = "1052">1052</option>
</select>
<p>{this.state.selectVal}</p>
</React.Fragment>
}
}
解决方案
你不能在课堂外使用你的状态。
但是,如果您坚持,您可以分别在初始加载和每次选择时使用 componentDidMount 和 componentDidUpdate 生命周期方法,并将 id 作为参数传递给fetchData
&chart_request
如下:
componentDidMount() {
// calling fetch, resolving the promise, and storing the data in state
fetchData(this.state.selectVal).then(data => this.setState({ data }));
}
componentDidUpdate() {
// same as above
fetchData(this.state.selectVal).then(data => this.setState({ data }));
}
chart_request
&的修改fetchData
:
const chart_request = id =>
fetch(
`https://xxxx.com/prod/job-id?job_id_number=${id}`
)
.then(response => response.json()) // instead of "jsonify"
.then(data => JSON.stringify(data))
.catch(error => error);
const fetchData = id => chart_request(id);
我已经修改了沙盒,所以你可以测试你的输出。
推荐阅读
- xamarin.forms - 贾维斯连接蓝牙
- git - 使用 git 我想将两个分支中的文件和历史记录复制到一个共同的父级中,但只能从特定文件夹中更改
- java - 如何在有更多 portlet 的页面上刷新 portlet?(liferay-7.2)
- excel - Excel VBA RemoveDuplicates 不起作用
- node.js - 快递问题:“,”是预期的,但添加时仍然显示错误
- javascript - 这些 Javascript Promise 链之间有什么区别?
- javascript - 在单击 Reactjs 中的按钮之前渲染组件
- c - 未定义对 fmod 的引用,错误 ld 返回 1 退出状态
- javascript - 实时时钟的 ERR_INSUFFICIENT_RESOURCES ajax 代码
- php - 停止免费订单的 WooCommerce 管理员电子邮件通知