不断违反规范:对象作为React子元素无效

时间:2019-04-19 14:16:06

标签: javascript reactjs asynchronous

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

  

不变违规:对象作为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);
    }
};

但没有异步/等待版本,我的代码正在工作:

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

1 个答案:

答案 0 :(得分:0)

  

但没有异步/等待版本,我的代码正常工作

async / await语法等效的内容将不使用任何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版本的功能相同。