【发布时间】:2022-11-24 08:02:12
【问题描述】:
我理解解构,它将数组中的值解压缩到变量中,并在 useState 中使用方括号意味着它在该数组中返回两个值,第一个是值,第二个是用于更改该值的函数, 但是我在使用自定义挂钩时看到 [],这对我来说没有任何意义,谁能解释一下为什么变量 [breeds] 周围有方括号。它在 useState 下声明。
const ANIMALS = ["bird", "cat", "dog", "rabbit", "reptile"];
export const SearchParams = () => {
const [location, setLocation] = useState("");
const [animal, setAnimal] = useState('');
const [breed, setBreed] = useState('')
const [pets, setPets] = useState([]);
const [breeds] = useBreedList(animal);
useEffect(() => {
requestPets();
},[animal])
async function requestPets() {
const res = await fetch(
`http://pets-v2.dev-apis.com/pets?animal=${animal}&location=${location}&breed=${breed}`
);
const json = await res.json();
console.info('json is '+JSON.stringify(json))
setPets(json.pets);
console.warn("pets are " + JSON.stringify(pets));
}
return (
<div className="search-params">
<form>
<label htmlFor="location">
Location
<input
id="location"
value={location}
placeholder="Location"
onChange={(e) => setLocation(e.target.value)}
/>
</label>
<label htmlFor="animal">
Animal
<select
id="animal"
value={animal}
onChange={(e) => {
setAnimal(e.target.value);
setBreed("");
}}
onBlur={(e) => {
setAnimal(e.target.value);
setBreed("");
}}
>
<option />
{ANIMALS.map((animal) => (
<option key={animal}>{animal}</option>
))}
</select>
</label>
<label htmlFor="breed">
Breed
<select
id="breed"
value={breed}
onChange={(e) => setBreed(e.target.value)}
disabled={breeds.length === 0}
>
<option />
{breeds.map((breed) => (
<option key={breed}>{breed}</option>
))}
</select>
</label>
<button>Submit</button>
</form>
{pets.map((pet) => (
<Pet
name={pet.name}
animal={pet.animal}
breed={pet.breed}
key={pet.id}
/>
))}
</div>
);
}
这是自定义挂钩
const localCache = {};
export const useBreedList = (animal) => {
const [breedList, setBreedList] = useState([]);
const [status, setStatus] = useState("unloaded");
useEffect(() => {
if (!animal) {
setBreedList([])
} else if (localCache[animal]) {
setBreedList(localCache[animal])
} else {
requestBreedList();
}
async function requestBreedList() {
setBreedList([]);
setStatus("loading");
const res = await fetch(
`https://pets-v2.dev-apis.com/breeds?animal=${animal}`
)
const json = await res.json();
localCache[animal] = json.breeds || []
setBreedList(localCache[animal]);
setStatus("loaded");
}
}, [animal]);
return [breedList, status];
}
【问题讨论】:
-
对我来说也没有意义。唯一的优点是重命名更短,但我会使用一个对象
标签: reactjs