【问题标题】:Cannot destructure an object fetched from api无法解构从 api 获取的对象
【发布时间】:2021-03-04 02:22:53
【问题描述】:

我获取了一个包含两个属性的对象,一个是数字,一个是数组。所以我立即访问了数组,然后分配了一个状态,然后通过上下文 api 将每个项目传递给另一个组件。它不工作。这是我的代码:

const [info, setInfo] = useState([]);
const [i, setI] = useState(0);

const fetchUrl = async() => {
    setLoading(true);
    const response = await fetch(url);
    const data = await response.json();
    setInfo(data.results);
    setLoading(false);
} 

useEffect(() => {
    fetchUrl();
}, []);

const {correct_answer, incorrect_answers, question} = info[i];
const arr = [correct_answer, ...incorrect_answers].sort((a, b) => a.length - b.length);

在此代码中,“correct_answer”是一个字符串,“incorrect_answers”是一个数组。 运行此代码后,它会说:

TypeError: Cannot destructure property 'correct_answer' of 'info[i]' as it is undefined.

有时它会说:

TypeError: 'incorrect_answers' is not iterable.

【问题讨论】:

    标签: javascript reactjs fetch react-context


    【解决方案1】:

    看起来你没有在任何地方定义i。您收到的错误是因为 info[i] 返回未定义。

    第二个错误可能是由于 incorrect_answers 未定义或不是数组。

    问题很可能是 fetchUrl 正在异步执行,而您正在设置这些可能依赖于 fetchUrl 完成的其他变量,而不是等待 fetchUrl 完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2021-05-19
      相关资源
      最近更新 更多