亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

反應錯誤:元素類型對命名導出無效

反應錯誤:元素類型對命名導出無效

倚天杖 2023-05-25 18:13:49
我通過反應鉤子和函數獲得了住宅區的速度,并且我有三個文件。一個提供上下文SummaryContext,第二個是使用上下文的類組件WikiSummary,第三個是顯示它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`.摘要上下文import React, { createContext } from 'react'export const SummaryContext = createContext(null);維基摘要import React, {Component} from "react";import {Title} from "./components/Title"import {SummaryContext} from "../../contexts/SummaryContext"import "../../App.css"class WikiSummary extends Component {render() {  return (    <>      <SummaryContext.Provider value = "hello from context">      <Title />      </SummaryContext.Provider>    </>  );}}export default WikiSummary;標題import React, {useContext} from "react"import {SummaryContext} from "../../../contexts/SummaryContext"export function Title(){  const message = useContext(SummaryContext)  return(    <div>      <h2>{message}</h2>    </div>  )}沙箱顯示與沙箱中不同的錯誤https://codesandbox.io/s/react-context-example-forked-rly0d?file=/src/components/Title.js
查看完整描述

2 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

SummaryContext.Consumer使用渲染道具,特別是一個函數作為子組件,因此它期望它的直接子組件是一個函數。

這就是你得到錯誤的原因,

類型錯誤:渲染不是函數。(在'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>一種方式,或者您也可以采用以前的方式將其分配給變量message并在模板內調用。


查看完整回答
反對 回復 2023-05-25
?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

我將reactreact-dom版本更新為 16.13.0 并刪除了SummaryContext.Consumer

如果您需要消費者 api 或無法升級反應版本,那么您應該將一個函數作為子函數傳遞給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>

? );

}


查看完整回答
反對 回復 2023-05-25
  • 2 回答
  • 0 關注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號