Как установить параметры в запросе get от реагировать - PullRequest
0 голосов
/ 28 апреля 2019

Может быть, это очень новый вопрос, но я трачу много времени, чтобы найти хороший подход для этого, и я не нашел удобного ответа.Я пытаюсь сделать простой вызов API остальных, и я хочу передать значение с GET-запросом, добавленным к строке.например, url / foo, где foo является параметром.У меня есть переменная запроса, которую я хочу добавить в конец строки URL для запроса get.Заранее спасибо.

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
    }




Ответы [ 3 ]

1 голос
/ 28 апреля 2019

Избавьтесь от лишних цитат (') в 'myurl/${this.state.query}'

0 голосов
/ 28 апреля 2019

Вы можете передать param без использования `` или $ также, в 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
                    });
                }
            )
    }
0 голосов
/ 28 апреля 2019
let query = {id:1};
let url = 'https:example.com//xyz.com/search?' + query;

 fetch(url)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...