【问题标题】:set Function not working in custom hook with useEffect使用 useEffect 设置函数在自定义钩子中不起作用
【发布时间】:2020-10-11 19:54:29
【问题描述】:

我正在开发一个依赖于 useEffect 中的异步操作的自定义挂钩。我无法让我的 set 函数实际设置异步操作结果的值。在这种情况下,我的 App 组件中的 country 始终为 null,因此不会渲染任何内容。 foundCountry 设置正确,但 setCountry 似乎不起作用。感谢您的帮助!

const useCountry = name => {
  const [country, setCountry] = useState([null]);

  useEffect(() => {
    const findCountry = async () => {
      const foundCountry = await axios.get(
        `https://restcountries.eu/rest/v2/name/${name}?fullText=true`
      );
      setCountry(foundCountry);
    };

    if (name !== '') findCountry();
  }, [name]);
};

这是我使用自定义钩子的应用组件

const App = () => {
  const nameInput = useField('text');
  const [name, setName] = useState('');
  const country = useCountry(name);

  const fetch = e => {
    e.preventDefault();
    setName(nameInput.value);
  };

  return (
    <div>
      <form onSubmit={fetch}>
        <input {...nameInput} />
        <button>find</button>
      </form>
      <Country country={country} />
    </div>
  );
};

【问题讨论】:

    标签: reactjs async-await use-effect


    【解决方案1】:

    您定义了自定义挂钩,但您忘记返回 country 状态作为结果:

    const useCountry = name => {
      const [country, setCountry] = useState([null]);
    
      useEffect(() => {
        const findCountry = async () => {
          const foundCountry = await axios.get(
            `https://restcountries.eu/rest/v2/name/${name}?fullText=true`
          );
          setCountry(foundCountry);
        };
    
        if (name !== '') findCountry();
      }, [name]);
    
      // you forgot to return it
      return country;
    };
    

    【讨论】:

    • 这绝对让我走上了正轨。我之前尝试过从 useEffect 返回国家/地区。谢谢!
    【解决方案2】:

    你可以试试这个

    const useCountry = name => {
        const foundCountry = await axios.get(
            `https://restcountries.eu/rest/v2/name/${name}?fullText=true`
        );
        if (name !== '') return findCountry();
        return;
    };
    
    //App container
    const [country, setCountry] = useState('');
    
    useEffect(() => {
        setCountry(useCountry(name))
    }, [name])
    

    【讨论】:

    • 我不相信您可以使用自定义挂钩作为回调。不过谢谢!
    猜你喜欢
    • 2021-09-10
    • 2021-10-16
    • 2022-10-09
    • 2020-05-23
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2020-03-23
    相关资源
    最近更新 更多