设置功能在使用useEffect的自定义挂钩中不起作用

时间:2020-06-22 01:25:15

标签: reactjs async-await use-effect

我正在使用依赖于useEffect中的异步操作的自定义钩子。我无法获得设置函数来实际设置异步操作结果的值。在这种情况下,国家/地区在我的App组件中始终为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]);
};

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

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>
  );
};

2 个答案:

答案 0 :(得分:0)

您定义了自定义钩子,但是忘记了返回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;
};

答案 1 :(得分:0)

您可以尝试

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])