挂钩状态的更改不会更新模板文字中的值

时间:2020-04-16 14:32:24

标签: reactjs react-hooks

我是钩子的新手,是在学习对课堂的反应之后来的,所以有点迷路了。在下面的代码中,我将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>
    );
}

3 个答案:

答案 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), []);