如何在 reactJS 的 get 请求中设置参数

也许这是一个非常新手的问题,但我花了很多时间来寻找这样做的好方法,但我没有找到方便的答案。我正在尝试对rest api进行简单的调用,并且我想传递一个带有附加到字符串的GET请求的值。像 url/foo 其中 foo 是参数。我有一个查询变量,我想将它附加到获取请求的 url 字符串的末尾。先感谢您。


class About extends React.Component {


    constructor(props) {

        super(props);

        this.state = {

            products: [],

            filteredItems: [],

            user: {},

            query: '' <-- query variable to be appended to the end of the get request

        };


    }




    componentDidMount() {


        fetch(`'myurl/${this.state.query}'`) <-- i want to append the variable at the end of the string ??

            .then(res => res.json())

            .then((result) => {

                    console.log(result);

                    this.setState({

                        products: result,

                        filteredItems: result

                    });

                }

            )

    }


    queryChange = (evt) => {

        this.setState({query: evt.target.value}) <-- update the variable state from an event

    }


收到一只叮咚
浏览 174回答 3
3回答

qq_笑_17

去掉多余的引号 (&nbsp;')'myurl/${this.state.query}'

慕姐4208626

您也可以在不使用 `` 或 $ 的情况下传递参数,在 componentDidMount()&nbsp; &nbsp;componentDidMount() {&nbsp; &nbsp; &nbsp; &nbsp; let query = this.state.query;&nbsp; &nbsp; &nbsp; &nbsp; fetch('myurl/'+query)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(res => res.json())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then((result) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(result);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; products: result,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filteredItems: result&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }

撒科打诨

let query = {id:1};let url = 'https:example.com//xyz.com/search?' + query;&nbsp;fetch(url)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java