简体   繁体   English

为什么我收到未定义的错误错误?

[英]Why am I a getting an error that react is undefined?

I'm new to react and I'm importing using esmodules but I keep getting an error telling react is undefined. 我是React的新手,正在使用esmodules导入,但是我不断收到错误消息,告知react未定义。 I'm running it through babel and then bundling it with webpack. 我正在通过babel运行它,然后将其与webpack捆绑在一起。 I've looked at some of the other related questions but none seem to be helping with my problem. 我已经看过其他一些相关的问题,但似乎都没有帮助解决我的问题。 Why is it comming up undefined and how can I fix it? 为什么会出现未定义的错误,我该如何解决?

Error: 错误:

Uncaught ReferenceError: React is not defined
    at Object.<anonymous> (bundle.js:formatted:76)
    at n (bundle.js:formatted:11)
    at bundle.js:formatted:71
    at bundle.js:formatted:72

package.json: package.json:

{
  "name": "reactTestProject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Brandon Lind",
  "license": "MIT",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  },
  "dependencies": {
    "@babel/polyfill": "^7.2.5",
    "react": "^16.8.4"
  }
}

files: 文件:

filename: app.js 文件名:app.js

 import Square from "./SquareDiv.js";

let main= document.getElementsByTagName("main")[0];
console.log("wtf")

main.appendChild(<Square/>);

filename: SquareDiv.js 文件名:SquareDiv.js

import React from "react";

class Square extends React.Component{
    constructor(props){
        super(props);
        this.state={
            isOn: true
        }
    }

    getIsOn(){
        let currentState= this.state.isOn;
        let pastState= state;
        if(currentState===false){
           currentState===true; 
        }
        else {
            currentState ===false;
        }

        return pastState;
    }

    render(){
        <div onClick={getIsOn} class="square">this.state.isOn</div>
    }
}

export {Square};

babel.config.js: babel.config.js:

const presets=[
    [
        "@babel/preset-env",
        {
            targets:{
                esmodules: true,
                edge: 10,
                chrome: 30,
                safari: 30,
                firefox: 30,
                opera: 30
            }
        }
    ],
    [
        "@babel/preset-react",
        {
                pragma: "pragma",
                pragmaFrag: "pragmaFrag",
                throwIfNamespace: false
        }
    ]
];


module.exports={
    presets
};

webpack.config.js: webpack.config.js:

module.exports={
    entry: "./src/app.js",
    output:{
        filename: "bundle.js"
    },
    module:{
        rules:[
            {  test: /\.m?js$/,
                exclude: /(node_modules|browsers_components)/,
                use:{
                    loader: "babel-loader",
                    options: {
                            presets: ["@babel/preset-env","@babel/preset-react"]
                    }
                }
            }
        ]
    }
}

Don't use this syntax import React from "./node_modules/react"; 不要使用这种语法import React from "./node_modules/react"; .

It will work only for files that are created in the root directory, and your components are likely in src/ . 它仅适用于在根目录中创建的文件,并且您的组件可能位于src/

Webpack will resolve everything for you, so you can just use import React from 'react'; Webpack将为您解决所有问题,因此您只需使用import React from 'react'; everywhere. 到处。

Also replace this string: export {Square}; 还要替换此字符串: export {Square}; with export default Square export default Square

And you can omit .js extension when import, so you can write it this way: import Square from "./SquareDiv"; 而且您可以在导入时省略.js扩展名,因此可以这样写: import Square from "./SquareDiv";

If you don't want to use default export, you should use import {Square} from "./SquareDiv" 如果您不想使用默认导出,则应使用import {Square} from "./SquareDiv"

You can read the differences between default and regular exports here 您可以在此处阅读默认导出和常规导出之间的区别

You have a lot of problems in your code snippet. 您的代码段中有很多问题。 I mentioned some of them in my answer. 我在回答中提到了其中一些。 There are more of them: 还有更多:

  • Don't use class keyword in JSX, it should be className 在JSX中不要使用class关键字,它应该是className
  • Use curly braces to render JS values like this.state.isOn 使用花括号将JS值呈现为this.state.isOn
  • When you use handlers, don't use it like onClick={getIsOn} , use onClick={() => getIsOn()} and etc. 使用处理程序时,请勿像onClick={getIsOn}onClick={() => getIsOn()}onClick={() => getIsOn()}那样使用它。

I suggest you to go through React tutorial which will save your time a lot! 我建议您阅读React教程 ,这将节省大量时间!

App.js needs to import react. App.js需要导入react。 Every file that has JSX in it has to import react. 每个包含JSX的文件都必须导入react。

This particular error is happening because the JSX for Square in app.js is getting transpiled into a React method call, and since you haven't imported React in app.js, React is not defined. 之所以发生此特定错误,是因为app.js中的Square的JSX被转换为React方法调用,并且由于您尚未在app.js中导入React,因此未定义React。

UPDATE 更新

Also, this will fix a couple other errors... 此外,这将修复其他一些错误...

Change <div onClick={getIsOn} class="square">this.state.isOn</div> to: <div onClick={getIsOn} class="square">this.state.isOn</div>更改为:

return <div onClick={this.getIsOn} className="square">{this.state.isOn}</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM