[英]useeffect function fetch multiple data
I am trying to fetch data from an API from an input.我正在尝试从输入中获取 API 中的数据。 After providing the input and calling the data, I am getting two fetch call from same data.
提供输入并调用数据后,我收到来自同一数据的两次提取调用。 here is the code of input:
这是输入代码:
const [countryName, setCountryName] = useState<string>("");
const handleInputChange = (event: {
target: { value: React.SetStateAction<string> };
}) => {
setCountryName(event.target.value);
};
const onSubmit = () => {
navigate(`/country/${countryName}`);
};
<TextField
variant="standard"
placeholder="Enter country Name"
value={countryName}
onChange={handleInputChange}
/>
Here I am using the input to fetch the data:这里我使用输入来获取数据:
const { name } = useParams();
const [loading, setLoading] = useState<boolean>(false);
const [country, setCountry] = useState<InitCountry>();
useEffect(() => {
const getCountry = async () => {
setLoading(true);
const response = await fetch(
`https://restcountries.com/v3.1/name/${name}`
);
const data = await response.json();
console.log(data);
setCountry(data.length > 1 ? data[2] : data[0]);
setLoading(false);
};
getCountry();
}, [name]);
What am I doing wrong here?我在这里做错了什么?
Your setup seems good, but the root cause is possibly from React.StrictMode
您的设置看起来不错,但根本原因可能来自
React.StrictMode
Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic.
严格模式无法自动为您检测副作用,但它可以通过使它们更具确定性来帮助您发现它们。 This is done by intentionally double-invoking the following functions: ...
这是通过有意地重复调用以下函数来完成的:...
This effect is only in development which means it won't happen in your production, but if you don't want intentionally double-invoking , you can remove it from your code.此效果仅在开发中,这意味着它不会在您的生产中发生,但如果您不想故意重复调用,则可以将其从代码中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.