【问题标题】:REact error Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array insteadREact 错误对象作为 React 子级无效(找到:[object Promise])。如果您打算渲染一组孩子,请改用数组
【发布时间】:2020-05-24 10:46:27
【问题描述】:

我正在尝试登录我的应用程序。但是我收到一条错误消息:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。 我可以登录,但我不想清除此错误。谢谢你的帮助

组件我的应用程序

import { ApolloProvider } from '@apollo/client'
import client from '../config/apollo'
import StateOrder from '../Context/Orders/StateOrder'
import '../styles.css'
const MyApp = ({ Component, pageProps }) => {
  return (
    <ApolloProvider client={client}>
      <StateOrder>
        <Component {...pageProps} />
      </StateOrder>
    </ApolloProvider>
  )
}
export default MyApp

组件索引

import Layout from '../Components/Layout'
import Client from '../Components/Client'
import { gql, useQuery } from '@apollo/client'
import { useRouter } from 'next/router'
import Link from 'next/link'

const GET_CLIENTS_BY_USER = gql`
query getClientsBySalesman{
  getClientsBySalesman{
    id
    name
    surname
    company
    email
  }
}`

const Index = () => {
  const router = useRouter()
  const { data, loading, error } = useQuery(GET_CLIENTS_BY_USER)

  if (loading) return <p className="my-2 bg-blue-100 border-l-4 border-blue-700 p-4 text-center">Carregant...</p>

  if (error || !data.getClientsBySalesman) {
    localStorage.removeItem('token');
    return router.push('/login')
  }

  return (
    <div>
      <Layout>
        <h1 className="text-2xl text-gray-800">Clients</h1>
        <Link href="/nouclient">
          <a className="bg-blue-800 py-2 px-5 mt-3 inline-block text-white rounded text-sm hover:bg-gray-800 uppercase w-full lg:w-auto text-center">Nou Client</a>
        </Link>
        <div className="sm:overflow-x-scroll">
          <table className="table-auto shadow-md mt-10 w-full w-lg">
            <thead className="bg-gray-800">
              <tr className="text-white">
                <th className="w-1/5 py-2">Nom</th>
                <th className="w-1/5 py-2">Empresa</th>
                <th className="w-1/5 py-2">Email</th>
                <th className="w-1/5 py-2">Eliminar</th>
                <th className="w-1/5 py-2">Editar</th>
              </tr>
            </thead>
            <tbody className="bg-white">
              {data.getClientsBySalesman.map(client => (
                <Client
                  key={client.id}
                  client={client} />
              ))}
            </tbody>
          </table>
        </div>
      </Layout>
    </div >
  )
}
export default Index

组件状态顺序

import React, { useReducer } from 'react'
import ContextOrder from './ContextOrder'
import ReducerOrder from './ReducerOrder'

import {
  SELECT_CLIENT,
  SELECT_PRODUCT,
  PRODUCT_QUANTITY,
  UPDATE_TOTAL
} from '../../types'

const StateOrder = ({ children }) => {
  const initialState = {
    client: {},
    products: [],
    total: 0
  }
  const [state, dispatch] = useReducer(ReducerOrder, initialState)
  const addClient = client => {
    dispatch({
      type: SELECT_CLIENT,
      payload: client
    })
  }

  const addProduct = selectProducts => {
    let newState
    if (state.products.length > 0) {
      newState = selectProducts.map(product => {

        const newObject = state.products.find(productState => productState.id === product.id);
        return { ...product, ...newObject }
      })
    } else {
      newState = selectProducts;
    }
    dispatch({
      type: SELECT_PRODUCT,
      payload: newState
    })
  }

  const productQuantity = newProduct => {
    dispatch({
      type: PRODUCT_QUANTITY,
      payload: newProduct
    })
  }

  const updateTotalOrder = () => {
    dispatch({
      type: UPDATE_TOTAL
    })

  }
  return (
    <ContextOrder.Provider
      value={{
        client: state.client,
        products: state.products,
        total: state.total,
        addClient,
        addProduct,
        productQuantity,
        updateTotalOrder
      }}
    >
      {children}
    </ContextOrder.Provider>
  )
}
export default StateOrder

【问题讨论】:

  • return router.push('/login') 导致了您的问题,去掉return 声明。

标签: reactjs graphql apollo


【解决方案1】:

你可以尝试这样的事情,我也犯了同样的错误,它对我有用。我的理解是,当您返回 router.push('/login') 时,next.js 的默认路由器会调用一个承诺,因此会生成异常。

if (!data.getClientsBySalesman) {
    window.location.href = 'login';
}

【讨论】:

    【解决方案2】:

    在名为 Index 的组件中,您正在检查错误,如果存在,您希望将 URL 更改为正确的“/login”,但是不是这样做,而是返回 router.push() 值。

    if (error || !data.getClientsBySalesman) {
        localStorage.removeItem('token');
        return router.push('/login')
    }
    

    由于这是一个函数式组件,一旦 React 遇到这个返回语句以防出现错误,React 就会假设这个返回值就是你想要渲染的。但是因为你不能只渲染对象。 React 为您提供有关渲染中存在无效子项的错误。

    【讨论】:

    • 如果我明白我必须删除退货。但是如果我删除返回,我可以更改 de url 但它不会重定向到登录组件和应用程序中断
    • 这很奇怪,它不应该发生,你能帮我提供上面示例的代码框链接吗?省略该 return 语句不应该破坏任何东西。它不太可能导致错误。附带说明一下,您可能会尝试在不使用路由器对象的情况下更改窗口 URL。看看这是否有效。虽然这不是处理它的理想方式。
    【解决方案3】:

    您只需删除 return 关键字,它就可以正常工作而不会引发错误:

     if (error || !data.getClientsBySalesman) {
        localStorage.removeItem('token');
        router.push('/login')
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      • 2021-09-28
      • 2021-12-10
      • 1970-01-01
      • 2020-12-22
      相关资源
      最近更新 更多