【问题标题】:How to set parameters in a get request from reactJS如何在 reactJS 的 get 请求中设置参数
【发布时间】:2019-04-28 16:25:41
【问题描述】:

也许这是一个非常新手的问题,但我花了很多时间来寻找这样做的好方法,但我没有找到方便的答案。我正在尝试对 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
    }




【问题讨论】:

  • 你在那里使用的东西不起作用吗?模板字符串看起来是一种很好的方法。
  • 实际上,当我提交表单时,我不知道如何调用 componentDidMount() 到目前为止这是我的问题。

标签: java reactjs rest get


【解决方案1】:

去掉'myurl/${this.state.query}'中多余的引号('

【讨论】:

    【解决方案2】:
    let query = {id:1};
    let url = 'https:example.com//xyz.com/search?' + query;
    
     fetch(url)
    

    【讨论】:

    • 好的,当我尝试附加在字符串末尾的 url + 查询时,我得到 SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 我试图获取硬编码的数据,我不要得到 json 解析错误..也从 url 中删除逗号,错误与其他内容相同
    • 欢迎来到 Stack Overflow!虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    • 感谢您的帮助,我的问题在其他地方,但 Avinash Mahlawat 和 ehutchllew 的回答对于所提出的问题非常有效。
    • 这是我的荣幸,我希望你也为我做同样的事情。
    【解决方案3】:

    在componentDidMount()中也可以不使用``或$来传递参数

       componentDidMount() {
            let query = this.state.query;
            fetch('myurl/'+query)
                .then(res => res.json())
                .then((result) => {
                        console.log(result);
                        this.setState({
                            products: result,
                            filteredItems: result
                        });
                    }
                )
        }
    

    【讨论】:

    • 好吧,当我发布表单 componentDidMount() {} 以触发并附加正确的 url + 查询时,我还发现了我所期望的错误,但事实并非如此。它对我来说可以在按钮的 onClick 事件中获取数据。换句话说,我将逻辑从 componentDidMount() 移到 onClick 函数中,它工作正常。
    • 是的,对不起,我忘记投票了。完毕。再次感谢您
    猜你喜欢
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 2019-07-19
    相关资源
    最近更新 更多