【问题标题】:Getting Invariant Violation: Objects are not valid as a React child获得不变违规:对象作为 React 子对象无效
【发布时间】:2019-09-09 19:22:12
【问题描述】:

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

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

【问题讨论】:

  • 我怀疑错误来自这段代码。请添加堆栈跟踪,并发布代码的相关部分 - 可能是 noteAction 和受影响组件的 render 方法?
  • 不,这与承诺或异步本身无关。
  • 当我使用 promise .then 版本时。它有效,当我使用 async/await 而不是旧的 Promise 版本时会发生错误。 @Bergi
  • 您说的是哪个“.then 版本”?请edit您的代码包含工作代码,以便我们进行比较。

标签: javascript reactjs asynchronous


【解决方案1】:

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

使用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 版本的工作方式相同。

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2020-01-25
    • 2018-12-16
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多