在同一组件中包装提供者抛出元素类型无效:应为字符串(对于内置组件)或 class/function 但得到:对象

Wrapping Provider in same component throws Element type is invalid: expected a string (for built-in components) or a class/function but got: object

我在 Mobx 和 Redux 中写了一个简单的计数器示例并且它有效

完整演示可用https://codesandbox.io/s/nw303w6jxl

但是如果我从 ./src/index.js

中删除 Provider
const App = () => (
  <div className="container">
    <Mobx />
    <hr />
    <Provider store={store}>
      <Redux />
    </Provider>
  </div>
);

& 将其放入 ./src/redux.js 而默认导出会引发错误

export default (
  <Provider store={store}>
    <ConnectReduxApp />
  </Provider>
);

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

可以正常工作,但我不知道为什么会这样?我检查了 typeof 来自 ./src/redux.js 的默认导出函数,即

console.log(
    typeof(
       <Provider store={store}>
         <ConnectReduxApp />
       </Provider>
    )
);

& 它是一个 object 但是如果我只想在我的 React 应用程序的一部分中使用 Redux 怎么办。让我们说一个表格。然后通过这种方式它会抛出错误。感谢您的帮助。

发生这种情况是因为您导出的不是返回 JSX 的函数,也不是带有 returns JSX 渲染方法的 class,您导出的是 JSX 本身。

要么像 {reduxImported}:

那样渲染它
import reduxImported from './src/redux.js'
...
render() {
  <Container>
    {reduxImported}
    <MobX />
  </Container>
}

或将导出更改为:

export default () => (
  <Provider store={store}>
    <ConnectReduxApp />
  </Provider>
)