反应错误:元素类型对于命名导出无效

时间:2020-10-19 10:57:15

标签: javascript reactjs

我正在使用React钩子和函数来提高速度,我有三个文件。一个提供了上下文O(n^2),第二个是使用了上下文n^2的类组件,第三个显示了O(n^2)

但是,我得到了以下错误,尽管我一整天都在混乱(仍然在学习),但我仍然不知道为什么会出现此错误。

SummaryContext

摘要上下文

WikiSummary

Wiki摘要

Title

标题

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `WikiSummary`.

沙箱显示的错误与sanbox中看到的不同

https://codesandbox.io/s/react-context-example-forked-rly0d?file=/src/components/Title.js

2 个答案:

答案 0 :(得分:1)

SummaryContext.Consumer使用一个渲染道具,特别是一个函数作为子组件,因此它希望其直接子对象是一个函数。

这是您收到错误的原因,

TypeError:render不是函数。 (在'render(newValue)','render' 是Object的实例)

在您的情况下,您只需将div移入函数之内即可,

import React from "react";
import { useContext } from "react";
import { SummaryContext } from "./SummaryContext";

export function Title() {
  const message = useContext(SummaryContext);

  return (
    <SummaryContext.Consumer>
      {(value) => (
        <div>
          <h2>{message}</h2>
        </div>
      )}
    </SummaryContext.Consumer>
  );
}

这里value本身也提供了您希望显示的消息,因此您可以直接使用<h2>{value}</h2>,也可以采用以前的方式将其分配给变量{{1} }和模板中的调用。

Edit React: Context Example (forked)

答案 1 :(得分:0)

https://codesandbox.io/s/react-context-example-forked-yrd7g?file=/src/components/Title.js

我将reactreact-dom的版本更新为16.13.0 并删除了SummaryContext.Consumer

如果您需要消费者api或无法升级react版本,则应将一个子函数传递给SummaryContext.Consumer

import React from "react";
import { useContext } from "react";
import { SummaryContext } from "./SummaryContext";

export function Title() {
  return (
    <SummaryContext.Consumer>
      {(value) => (
        <div>
          <h2>{value}</h2>
        </div>
      )}
    </SummaryContext.Consumer>
  );
}