gpt4 book ai didi

javascript - 即使 API 获得新参数,React setState 也不会更新

转载 作者:行者123 更新时间:2023-12-02 21:45:54 25 4
gpt4 key购买 nike

我正在使用的此网络应用程序遇到问题。

https://food-search-octavian.netlify.com/

现在,在食谱页面 https://food-search-octavian.netlify.com/recipes我的搜索实际上不起作用。它绑定(bind)到有效的 Enter 键,请求本身有效,但是当我尝试将状态设置为新搜索时,它不会更新。

这是组件中的代码:

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 是异步的,但我在网络应用程序的其他页面上有确切的逻辑并且它可以工作。

最佳答案

我猜这是您的 getRecipes 函数。 React 的 setState “异步,但在 javascript async/await 意义上不是。它更像是当前渲染周期期间的状态更新已排队以便在下一个渲染周期进行处理。

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,并返回(可能) Unresolved Promise,当请求解析时(任意数量的渲染周期之后),它会再次更新状态加载 false 并使用配方。

codesandbox

编辑在codesandbox中,两种方法都可以工作,所以也许您没有正确接收/处理响应数据,或者您有一个格式错误的请求。

关于javascript - 即使 API 获得新参数,React setState 也不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60251334/

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