【发布时间】:2020-10-11 19:54:29
【问题描述】:
我正在开发一个依赖于 useEffect 中的异步操作的自定义挂钩。我无法让我的 set 函数实际设置异步操作结果的值。在这种情况下,我的 App 组件中的 country 始终为 null,因此不会渲染任何内容。 foundCountry 设置正确,但 setCountry 似乎不起作用。感谢您的帮助!
const useCountry = name => {
const [country, setCountry] = useState([null]);
useEffect(() => {
const findCountry = async () => {
const foundCountry = await axios.get(
`https://restcountries.eu/rest/v2/name/${name}?fullText=true`
);
setCountry(foundCountry);
};
if (name !== '') findCountry();
}, [name]);
};
这是我使用自定义钩子的应用组件
const App = () => {
const nameInput = useField('text');
const [name, setName] = useState('');
const country = useCountry(name);
const fetch = e => {
e.preventDefault();
setName(nameInput.value);
};
return (
<div>
<form onSubmit={fetch}>
<input {...nameInput} />
<button>find</button>
</form>
<Country country={country} />
</div>
);
};
【问题讨论】:
标签: reactjs async-await use-effect