首页 > 解决方案 > 如何根据所选选项在 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>
    }
}

标签: reactjs

解决方案


你不能在课堂外使用你的状态。

但是,如果您坚持,您可以分别在初始加载和每次选择时使用 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);

我已经修改了沙盒,所以你可以测试你的输出。


推荐阅读