为什么我的状态无法使用React Hooks更新? [英] Why is my state not being updated using React Hooks?
本文介绍了为什么我的状态无法使用React Hooks更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将状态设置为从API提取的数据.但是,当我用console.log记录状态(在这种情况下为 items
)时,它将返回一个空数组.
I'm trying to set my state to data fetched from an API. However when I console.log the state (items
in this instance), it returns an empty array.
这是我的代码:
const Search = () => {
const apiKey = 'xxxxxxx';
const [input, setInput] = useState('');
const [items, setItems] = useState([]);
const handleSubmit = (e) => {
searchAPI();
};
const searchAPI = async () => {
const res = await fetch(`http://www.omdbapi.com/?apikey=${apiKey}&s=${input}`);
const data = await res.json();
setItems([data.Search]);
console.log(items)
};
return (
<form>
<input onChange={(e) => setInput(e.target.value)}></input>
<Link to={{ pathname: '/results', state: items }}>
<button type="submit" onClick={handleSubmit}>
search
</button>
</Link>
</form>
);
};
推荐答案
因为setState是异步的
Because setState is asynchronous
setState()并不总是立即更新组件.它可能批处理或将更新推迟到以后.这使得阅读this.state在调用setState()之后立即陷入陷阱
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall
https://reactjs.org/docs/react-component.html#setstate
这篇关于为什么我的状态无法使用React Hooks更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文