将参数添加到url。让网址动态化

时间:2018-01-30 09:25:50

标签: javascript reactjs ecmascript-6

我有一个函数,我正在尝试将id参数添加到url并动态更改url并向其添加id参数。但使用花括号并不反映参数。

submitRating(rate, id) {
  this.setState({
    rating: rate,
  });
  console.log(this.state.rating);
  console.log(id);    ------> the console calls the id eg. id = 3499583
  const url = "https://oversight-ws.herokuapp.com/api/politicians/{id}/rating"  ---> that id should be rendered here on {id}
  console.log(url); ---> i want to return this url https://oversight-ws.herokuapp.com/api/politicians/3499583/rating
  return;

4 个答案:

答案 0 :(得分:1)

const id = 1

const url = `https://oversight-ws.herokuapp.com/api/politicians/${id}/rating`

file

答案 1 :(得分:1)

您正在使用es6,因此您可以使用字符串插值来执行此操作:

const id = 3499583;
const url = `https://oversight-ws.herokuapp.com/api/politicians/${id}/rating`;
console.log(url);

答案 2 :(得分:0)

使用ES6并参考this,你就像这样写

const id = 3499583;
const url = `https://oversight-ws.herokuapp.com/api/politicians/${id}/rating`;

答案 3 :(得分:0)

您可以使用ES2015模板文字功能。

Template Literals MDN

`string text ${expression} string text`

` => back-tick on keyboard

${} => placeholder within template

const url = `https://oversight-ws.herokuapp.com/api/politicians/${id}/rating`

=============================================== ============================

submitRating(rate, id) {
  this.setState({
    rating: rate,
  });
  console.log(this.state.rating);
  console.log(id);    ------> the console calls the id eg. id = 3499583
  const url = `https://oversight-ws.herokuapp.com/api/politicians/${id}/rating`  ---> that id should be rendered here on {id}
  console.log(url); ---> i want to return this url https://oversight-ws.herokuapp.com/api/politicians/3499583/rating
  return;