开发者问题收集

未捕获的类型错误:无法读取 null 的属性(读取“useContext”)

2022-05-28
64467

因此,在我的 React 代码中,我没有使用 useContext 属性。我有一个 npm 包,里面有一个编译好的 webpack 文件,里面有一个组件。当我尝试在我的 React 应用程序中使用该组件时,它会抛出错误 Uncaught TypeError: Cannot read properties of null (reading 'useContext')。组件函数在那里并输出一个 React 对象。使用它时只会破坏页面。现在我研究了 useContext 是什么,我相信它与状态有关。

所以下面是我将在 React App 中使用的输入组件

import React from 'react';
import {TextField} from  '@mui/material';
class Input extends React.Component {
  constructor(props){
    super(props)
  }
  render(){
    return (
      <div className="input" style={{position:"relative",left:this.props.tabOver? this.props.tabOver.toString()+"px":"0px"}}>
        <label style={{display:"block", width:"100%",position:"relative", margin: "5px"}}> {this.props.labelName}</label>
        <TextField
        size="small"
        onChange={(e)=>{this.props.update(e.target.value)}}
        value={this.props.value}
        label={this.props.label? this.props.label:"type here"}
        error={this.props.error? this.props.error:false}
        required={this.props.required? this.props.required:false}
        disabled={this.props.disabled? this.props.disabled:false}
        helperText={this.props.helperText? this.props.helperText:""}
        InputProps={{ style: { fontSize: this.props.InputProps? this.props.InputProp:10 } }}
        InputLabelProps={{ style: { fontSize: (this.props.InputLabelProps? this.props.InputLabelProps:12) } }}
        style={{background:'white', "borderLeft":"20px solid "+this.props.border,"borderRadius": "10px",width: this.props.width !== undefined ? this.props.width.toString()+"px":"100px"}}
        id="filled-basic"
        variant="filled" />
      </div>
    );
  }
}
export default Input;

这是我使用输入的 React 应用程序

// import logo from './logo.svg';
import './App.scss';
import React from 'react';
import {Breadcrumbs,Link,Typography} from  '@mui/material';
import {Input} from '@zenaby/something';

class App extends React.Component {
  constructor(props){
    super(props)
   }

  render(){
    return (
      <div className="App">
        <ul className="header">
          <li> logo </li>
          <li> login </li>
        </ul>
        <div className="formCt">
         <Input />        
        </div>
      </div>
    );
  }
}
export default App;

我使用此 webpack 文件编译了此输入

const path = require('path'); 
module.exports = {
  entry: "./compile/index.js",
  mode:"production",
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "index.js", 
    libraryTarget: "commonjs2" 
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-react",
            "@babel/preset-env"],
            plugins: ["@babel/plugin-proposal-class-properties"]
          }
        }
 }
 ]
  },
  target: 'node'
};

我的包 json 也在这里

{
  "name": "somename",
  "version": "0.1.0",
  "private": false,
  "babel": {
    "presets": [
      "@babel/preset-react"
    ]
  },
  "main":"dist/header.js",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "react-dom": "^18.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "pp": "babel .components -d ./dist --ignore 'node_modules'",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "description": "This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).",
  "author": "grant",
  "license": "ISC",
  "peerDependencies": {
    "react": "^18.1.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.17.10",
    "@babel/plugin-syntax-jsx": "^7.17.12",
    "@babel/preset-react": "^7.17.12"
  }
}

我希望这是一个简单的答案,但是在这个问题上花了几个小时,我没有任何精力去弄清楚。事实上,这个答案可能对很多刚开始为 npmjs 制作组件的人有帮助。无论如何,感谢您查看它,任何反馈都很棒:)。

3个回答

如果软件包安装在不同的级别,则经常会发生这种情况。

错误

app
 |node_modules          <-- some packages installed here
 |package.json
node_modules
package.json            <-- some packages installed here

正确方法

app
 |node_modules
 |package.json          <-- install all the packages at the same heirarchy
krishnaacharyaa
2022-10-07

答案是我忘记删除其他包中的 node_modules,并且 react 被重复,也引发了错误,提示 react hooks 错误。 React hooks 重复 react 包

Grant mitchell
2022-05-29

2023 年 1 月:

我也遇到了此错误 无法读取 null 的属性(读取“useContext”)

我通过将 'rollup-plugin-peer-deps-external' 添加到我的 rollup.config.mjs 解决了此问题

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import dts from 'rollup-plugin-dts';
import PeerDepsExternalPlugin from 'rollup-plugin-peer-deps-external';  //<--- THIS

import packageJson from "./package.json" assert {type: 'json'};

export default [
    {
        input: "src/index.ts",
        output: [
            {
                file: packageJson.main,
                format: "cjs",
                sourcemap: true,
            },
            {
                file: packageJson.module,
                format: "esm",
                sourcemap: true,
            },
        ],
        plugins: [
            PeerDepsExternalPlugin(),              //<--- THIS
            resolve(),
            commonjs(),
            typescript({ tsconfig: "./tsconfig.json" }),
        ],
    },
    {
        input: "dist/esm/types/index.d.ts",
        output: [{ file: "dist/index.d.ts", format: "esm" }],
        plugins: [dts()],
    },
];
gantonioid
2023-01-19