无法解构对象

Cannot destructure an object

我获取了包含两个属性的对象,一个是数字,一个是数组。所以我马上访问数组,然后分配给一个状态,然后通过上下文 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.

我该如何解决这个问题?

您正试图解构一个尚不存在的数组元素。您可以使用此解决方法:

const {correct_answer, incorrect_answers = [], question} = info[i] || {};

请注意,在您收到 api 的响应之前,属性等于未定义。同样在这里您可以看到我为 incorrect_answers 属性 分配了一个默认值,因此它可以在进一步的代码中传播。