useContext始终未定义

时间:2020-04-29 20:52:43

标签: reactjs

为什么useContext未定义?

上下文

import React from 'react'

const PathContext = React.createContext()

export default PathContext

来自jsx文件

import PathContext from '../../../contexts/pathContext';

.......


 <PathContext.Provider
   value={{
     paths,
     pathChecks
   }}
  >
     <MyComponent />
  </PathContext.Provider>

MyComponent.jsx渲染功能中。

import PathContext from 'path/to/file';
import {useContext} from 'react';

const {
   paths,
   pathChecks
} = useContext(PathContext);

未定义!

我的上下文未定义是什么?

4 个答案:

答案 0 :(得分:0)

我认为您需要使用{useContext} from 'react'而不是{useContext} from React

答案 1 :(得分:0)

像这样使用它:

App.js (或主要组件)

// App.js
import React from "react";
import MyContext from "./PathContext";
import MyComponent from "./MyComponent";

export default function App() {
  return (
    <div className="App">
      <MyContext>
        <MyComponent />
      </MyContext>
    </div>
  );
}

PathContext.js

// PathContext.js
import React, { createContext } from "react";
export const PathContext = createContext(); // regular export

// A new component that will hold the context values and will wrap your <MyComponent>
const MyContext = ({ children }) => {
  const paths = "define your paths";
  const pathChecks = "define your pathChecks";

  return (
    <PathContext.Provider
      value={{
        paths,
        pathChecks
      }}
    >
      {children} // Pass children props
    </PathContext.Provider>
  );
};

export default MyContext; // default export MyContext component 

MyComponent.js (上下文使用者)

// MyComponent.js
import React, { useContext } from "react";
import { PathContext } from "./PathContext";

const MyComponent = () => {
  const { paths, pathChecks } = useContext(PathContext);

  return (
    <div>
      <div>{paths} value</div>
      <div>{pathChecks} value</div>
    </div>
  );
};

export default MyComponent;

这是一个 sandbox 示例。

答案 2 :(得分:0)

请检查此示例。一切正常。

import React, {useContext, useEffect, useReducer, useState} from 'react';
import PathContext from "./PathContext";

function PathContextExample() {
    const paths = 'this is path';
    const pathChecks = 'this is path checks';

    return (
        <div>
            <PathContext.Provider
                value={{
                    paths,
                    pathChecks
                }}
            >
                <MyComponent/>
            </PathContext.Provider>
        </div>
    )
}

export default PathContextExample;


function MyComponent() {

    const {
        paths,
        pathChecks
    } = useContext(PathContext);

    return (
        <div>
            {paths}
            <br/>
            {pathChecks}
        </div>
    )
}

答案 3 :(得分:0)

在MyComponent.jsx文件中,您应该导入 PathContext