首页 > 解决方案 > 获得不变违规:对象作为 React 子对象无效

问题描述

我的代码不起作用,它总是返回

Invariant Violation:对象作为 React 子对象无效(发现:具有键 {_40、_65、_55、_72} 的对象)。如果您打算渲染一组子项,请改用数组。

那里有任何错误的语法或逻辑吗?这是我的代码:

const asyncTest1= async() => {
    try {
        noteAction({ type: SET_LOADING, payload: true });
        const response = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('Async Test Load');
            }, 3000);
        });
        const adding = noteAction({ type: ADD_NOTE, payload: response });
        const setLoadingFalse = noteAction({ type: SET_LOADING, payload: false });
        const result = await Promise.all([response, adding, setLoadingFalse]);
        return result;
    } catch (e) {
        console.log(e);
    }
};

但没有 async/await 版本,我的代码正在运行:

  const asyncTest2= () => {
        try {
            noteAction({ type: SET_LOADING, payload: true });
            const result = new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve('Async Test Load');
                }, 3000);
            });
            return result
            .then(response => noteAction({ type: ADD_NOTE, payload: response }))
            .then(response => noteAction({ type: SET_LOADING, payload: false }));
        } catch (e) {
            console.log(e);
        }
    };

标签: javascriptreactjsasynchronous

解决方案


但没有异步/等待版本,我的代码正在运行

async与/语法的等价物await不会使用 any Promise.all,它会是

const asyncTest2 = () => {
    try {
        noteAction({ type: SET_LOADING, payload: true });
    } catch (e) {
        console.log(e);
    }
    var result = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Async Test Load');
        }, 3000);
    });
    var response = await result;
    var response = await noteAction({ type: ADD_NOTE, payload: response }));
    return noteAction({ type: SET_LOADING, payload: false }));
};

我不知道这是否是您真正想要的,但至少它与then版本相同。


推荐阅读