【问题标题】:React Context not working: is not defined no-undefReact Context 不工作:未定义 no-undef
【发布时间】:2020-12-12 16:45:06
【问题描述】:

为什么我的 Context 在 React 中不起作用?在下面收到一个未定义的错误。

import React, { useContext }  from 'react';

function BookList() {
  const PrintContext = React.createContext("CAR");

  const list = [
    { title: 'ABCDE', author: 'John Smith' }
  ]

  return (
    <PrintContext.Provider value="APPLE">
    <ul>
      {list.map((book, i) => <Book title={book.title} author={book.author} key={i} />)}
    </ul>
    </PrintContext.Provider>
  )
}

function Book(props) {
  const theme = useContext(PrintContext)
  return (
    <li>
      <h2>{theme}</h2>
      <h2>{props.title}</h2>
      <div>{props.author}</div>
      <input value={props.year} />
    </li>
  )
}

接收错误:

'PrintContext' 未定义 no-undef

使用最新版本的 React

资源:

React context - 'contextType' is not defined

【问题讨论】:

  • 嗨@PrãtéékThápá 它有效,请随时回答,我可以发送积分,谢谢!
  • 普通的 JavaScript 购物仍然适用。

标签: reactjs


【解决方案1】:

将您的 PrintContext 置于Booklist 函数的范围之外。

import React, { useContext }  from 'react';

const PrintContext = React.createContext("CAR");

function BookList() {

  const list = [
    { title: 'ABCDE', author: 'John Smith' }
  ]

  return (
    <PrintContext.Provider value="APPLE">
    <ul>
      {list.map((book, i) => <Book title={book.title} author={book.author} key={i} />)}
    </ul>
    </PrintContext.Provider>
  )
}

function Book(props) {
  const theme = useContext(PrintContext)
  return (
    <li>
      <h2>{theme}</h2>
      <h2>{props.title}</h2>
      <div>{props.author}</div>
      <input value={props.year} />
    </li>
  )
}

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2019-11-10
    • 2019-10-05
    • 2018-03-18
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多