useeffect 函数获取多个数据
useeffect function fetch multiple data
我正在尝试从输入的 API 中获取数据。提供输入并调用数据后,我收到来自同一数据的两次提取调用。这是输入代码:
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}
/>
这里我使用输入来获取数据:
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]);
我做错了什么?
您的设置似乎不错,但根本原因可能来自 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: ...
此效果仅在开发中,这意味着它不会出现在您的生产中,但如果您不想有意double-invoking,您可以将其删除来自您的代码。
我正在尝试从输入的 API 中获取数据。提供输入并调用数据后,我收到来自同一数据的两次提取调用。这是输入代码:
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}
/>
这里我使用输入来获取数据:
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]);
我做错了什么?
您的设置似乎不错,但根本原因可能来自 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: ...
此效果仅在开发中,这意味着它不会出现在您的生产中,但如果您不想有意double-invoking,您可以将其删除来自您的代码。