【发布时间】: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() 到目前为止这是我的问题。