未捕获的错误:元素类型无效:期望一个字符串(对于内置组件)或类/函数(对于复合组件)但得到:对象

时间:2018-04-22 18:16:42

标签: reactjs

Reactjs上下文提供程序错误

我收到以下错误

  

invariant.js:42 Uncaught Error:元素类型无效:期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:object。

这是我的app.js

import React from 'react';
import ReactDOM from 'react-dom';
import { UserProvider } from "./lib/user.js"

const App = () => <UserProvider></UserProvider>

ReactDOM.render(
  <App />,
  document.getElementById("app")
);

这是./lib/user.js

import React from 'react'

export const UserContext = React.createContext({
  user: null,
  logIn: ((token, user) => {}),
  logOut: (() => {})
})

export class UserProvider extends React.Component {
  constructor(props) {
    super(props)

    this.logIn = (token, user) => {
      setToken(token)
      this.setState(state => ({user: user}))
    }

    this.logOut = (client) => {
      clearToken()
      this.setState(state => ({user: null}))
      client.resetStore()
      client.cache.reset()
    }

    this.state = {
      user: null,
      logIn: this.logIn,
      logOut: this.logOut
    }
  }

  render() {
    console.log(<div></div>)
    console.log(<UserContext.Provider/>)
    return (
      <UserContext.Provider value={this.state}>
        <p>hi</p>
      </UserContext.Provider>
    )
  }
}

这是在React 16.3.2上。在许多情况下,错误是由默认与命名导出造成的,这似乎不是:

  1. Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object
  2. Uncaught Error: Element type is invalid: expected a string (for built-in components)
  3. Element type is invalid: expected a string (for built-in components) or a class/function

1 个答案:

答案 0 :(得分:4)

您可能正在使用react@16.3版本之前的react-dom版本(例如16.2)但尚不支持上下文。