我是钩子的新手,是在学习对课堂的反应之后来的,所以有点迷路了。在下面的代码中,我将setDog更改为Husky,然后应告诉API调用以搜索并获取我的哈士奇照片。但是尽管狗变了,它也没有发生。谁能看到我要去哪里错了?
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function ApiCalls() {
const [ data, setData ] = useState();
const [ dog, setDog ] = useState('labrador');
useEffect(() => {
const fetchData = async () => {
const result = await axios(`https://dog.ceo/api/breed/${dog}/images`);
setData(result.data.message[0]);
};
fetchData();
}, []);
const Husky = () => {
setDog('husky');
};
return (
<div>
<img alt={''} src={data} />
<button onClick={Husky}>Retrieve Husky</button>
</div>
);
}
答案 0 :(得分:1)
您的useEffect敏感度列表为[],因此此useEffect仅在dog变量为labrador
的组件装载上运行。因此,在您更改按钮上的dog后,将不会从服务器获取新内容。如下更改代码:
useEffect(() => {
const fetchData = async () => {
const result = await axios(`https://dog.ceo/api/breed/${dog}/images`);
setData(result.data.message[0]);
};
fetchData();
}, [dog]);
答案 1 :(得分:1)
useEffect
仅运行一次,因为依赖项数组为[]
为空。因此,当您更改dog
时,它不会触发。要解决此问题,请将dog
添加到useEffect依赖项
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function ApiCalls() {
const [ data, setData ] = useState();
const [ dog, setDog ] = useState('labrador');
useEffect(() => {
const fetchData = async () => {
const result = await axios(`https://dog.ceo/api/breed/${dog}/images`);
setData(result.data.message[0]);
};
fetchData();
}, [dog]);
const Husky = () => {
setDog('husky');
};
return (
<div>
<img alt={''} src={data} />
<button onClick={Husky}>Retrieve Husky</button>
</div>
);
}
答案 2 :(得分:0)
执行此操作
const fetchData = async (input) => {
const result = await axios(`https://dog.ceo/api/breed/${input}/images`);
setData(result.data.message[0]);
};
useEffect(() => fetchData(dog), []);