Javascript API不响应设置状态';即使得到新的参数,也不能更新
我正在使用的web应用程序有问题 现在,在菜谱页面上,我的搜索实际上不起作用。它绑定到输入有效的键,请求本身有效,但当我尝试将状态设置为新搜索时,它不会更新 这是组件中的代码:Javascript API不响应设置状态';即使得到新的参数,也不能更新,javascript,reactjs,Javascript,Reactjs,我正在使用的web应用程序有问题 现在,在菜谱页面上,我的搜索实际上不起作用。它绑定到输入有效的键,请求本身有效,但当我尝试将状态设置为新搜索时,它不会更新 这是组件中的代码: this.state = { recipes: [], search: "chicken", loading: false, height: 0 }; this.getRecipes = this.getRecipes.bind(this); th
this.state = {
recipes: [],
search: "chicken",
loading: false,
height: 0
};
this.getRecipes = this.getRecipes.bind(this);
this.changeActive = this.changeActive.bind(this);
}
componentDidMount() {
this.getRecipes(this.state.search);
}
componentDidUpdate(prevProps, prevState) {
if (prevState.search !== this.state.search) {
this.getRecipes(this.state.search);
}
}
changeActive(newSearch) {
this.setState({
search: newSearch
});
}
getRecipes = async e => {
this.setState({
loading: true
});
await recipesRequest(e).then(response => {
this.setState({
recipes: response,
loading: false
});
});
};
这是请求的代码:
const axios = require("axios");
const recipesRequest = param => {
let api_key = "*";
let api_id = "*";
return axios
.get(
`https://api.edamam.com/search?q=chicken&app_id=${api_id}&app_key=${api_key}`,
{
headers: {
"Content-Type": "application/json"
}
}
)
.then(function(response) {
return response.data.hits;
});
};
export default recipesRequest;
这是具有更新第一个组件中活动状态的搜索的组件:
this.state = {
input: ""
};
this.checkInput = this.checkInput.bind(this);
this.newSearch = this.newSearch.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
checkInput(e) {
var value = e.target.value;
this.setState({
input: value
});
}
handleKeyDown = e => {
if (e.key === "Enter") {
console.log(e.key);
let choice = this.state.input;
this.newSearch(choice);
}
};
newSearch(choice) {
this.props.changeActive(choice);
this.setState({
input: ""
});
}
据我所知,setState是异步的,但我在我的web应用程序的另一个页面中有一些确切的逻辑,它可以工作。我猜这是你的
getRecipes
函数。React的setState
是“异步的,但在javascript异步/等待的意义上不是”。它更像是当前渲染周期中的状态更新排队等待下一个渲染周期处理
getRecipes = async e => {
this.setState({
loading: true
});
await recipesRequest(e).then(response => {
this.setState({
recipes: response,
loading: false
});
});
};
在这里,您正在等待已排队的状态更新的执行,这些更新通常在函数返回后处理。请不要等待
getRecipes = e => {
this.setState({
loading: true
});
recipesRequest(e).then(response => {
this.setState({
recipes: response,
loading: false
});
});
};
这允许进行异步提取,但它正确地允许状态更新排队。状态将更新加载为true,并返回(可能)未解析的承诺,当请求解析时(稍后的渲染周期数),它将再次更新状态加载false和配方
编辑
在codesandbox中,这两种方法都有效,因此可能您没有正确接收/处理响应数据,或者您的请求格式不正确。哦,伙计,谢谢您的回复。毕竟我很笨,它可以使用异步或不使用异步,但我没有在Recipes请求中传递参数,它被默认设置为chicken:imdumb: