首页 > 解决方案 > 如何在 React 组件内的另一个函数中访问 useEffect 的异步数据

问题描述

我有一个带有 Hooks 的功能组件:

const Filters = () => {
  const [options, setOptions] = useState([]);

  const getOption = type => options.find(el => el.name === type);

  useEffect(() => {
    fetch('someURL')
      .then(resp => resp.json())
      .then(result => setOptions(result.data), error => console.log(error));
    // trying to check options array now
    console.log(getOption('type')); // returns undefined
  }, []);
}

这种方法的目的是获取数据,然后通过计算函数运行该数据,以获取基于getOption(type). 如果我使用,那么我将获得带有输出的useEffect(() => fetch(), [options]);无限循环。console.log()

所以,setOptions(result.data)我猜是异步的,就像setState在类组件中一样,但不接受在异步请求完成时使用的第二个参数。

我想在我的函数完成options后修改我的数组。fetch()getOption()

标签: javascriptreactjsreact-hooks

解决方案


您可以在修改时使用另一个useEffect执行功能options

const Filters = () => {
  const [options, setOptions] = useState([]);

  const getOption = type => options.find(el => el.name === type);

  useEffect(() => {
    fetch('someURL')
      .then(resp => resp.json())
      .then(result => setOptions(result.data), error => console.log(error));
  }, []);

  useEffect(() => {
    if (!options) {
      return;
    }

    console.log(getOption('type'));
  }, [options])
}

推荐阅读