gpt4 book ai didi

javascript - 将变量传递给 componentDidMount

转载 作者:行者123 更新时间:2023-12-02 21:24:18 26 4
gpt4 key购买 nike

我正在尝试更新 componentdidmount 中的 fetch API 调用以匹配 React 中的输入,但我很难将输入传递到 URl 的模板文字中。有人可以解释一下吗?

代码-

search(x) {
console.log(this.state);
console.log(x);
}

async componentDidMount() {
let food = 'cheese';
const url = `https://edamam-food-and-grocery-database.p.rapidapi.com/parser?ingr=${food}`;
fetch(url, {
method: 'GET',
headers: {
'x-rapidapi-host': 'edamam-food-and-grocery-database.p.rapidapi.com',
'x-rapidapi-key': 'removed for privacy'
}
})
.then((response) => response.json())
.then((data) => console.log(data.hints));
}

最佳答案

看起来您可能正在尝试做这样的事情。关键是 componentDidUpdate 响应状态的任何更改,因此如果您使用输入中的新值更新状态,它将运行。

class Thing extends React.Component {

constructor(props) {
super(props);

// Set up the state with food and data properties
this.state = { food: '', data: [] };
this.handleSearch = this.handleSearch.bind(this);
}

// Have a separate method for your API call that can
// grab the food from state and build then endpoint
doApiCall () {
const { food } = this.state;
return fetch(`https://something.com/${food}`);
}

// componentDidUpdate is called after
// a state change call. It calls the api method and then
// updates the state with the data
async componentDidUpdate() {
const response = await this.doApiCall();
const data = await reponse.json();
this.setState({ data });
}

// When the input is changed, update the state
// (which causes componentDidUpdate to run)
handleSearch(e) {
const { target: { value } } = e;
this.setState({ food: value });
}

render () {

return (
<div>
<input type="string" onChange={this.handleSearch} />
</div>
);

}

}

关于javascript - 将变量传递给 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60775759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com