Tag Archives: react.js

[Solved] React Startup Error at the First time :SyntaxError: Unexpected token

[react] prompt syntaxerror: unexpected token

1. background

Use react scaffold to build the project

  • Install globally: npm i -g create-react-app
  • create-react-app hello-react
  • Go to the project folder: cd hello-react
  • Start the project: npm start

When executing npm start, an error occurred, please check the node version.

 

2. problem-solving

  • The investigation found that it was caused by the node version.
  • execute node -v ;

  • react-app requires node version greater than 14
  • execute nvm use 14;

  • Just restart.

JavaScript Common Errors List (Reasons & Solutions)

Here is a list of the most common errors in JavaScript.

 

JavaScript Common Errors List

1.Uncaught TypeError: Cannot read property

Improper initialization of the state when reading the properties of an undefined object or calling its methods or rendering UI components will appear in the console

The simplest Solution: initialize state in the constructor.

2. TypeError: ‘undefined’ is not an object

An error occurred while reading a property or calling a method on an undefined object in safari.

3. TypeError: null is not an object

An error occurred while reading a property or calling a method on an empty object in Safari

Note: in JavaScript, null and undefined are different, which is why we see two different error messages. Undefined is usually a variable that has not been allocated, and null means the value is empty.

4.  (unknown): Script error

This kind of script error occurs when an uncaught JavaScript error (an error caused by the window.oneror handler rather than captured in the try catch) is restricted by the browser’s cross domain policy.

5. TypeError: Object doesn’t support property

The error in ie when calling an undefined method is equivalent to the “typeerror:” undefined “isnotafunction” error in chrome.

6. TypeError: ‘undefined’ is not a function

This is an error in chrome when calling an undefined function.

7. Uncaught RangeError

This error occurs when calling a recursive function that does not terminate, or if you pass a value to a function that is out of range.

8. TypeError: Cannot read property ‘length’

An error occurred while reading the length attribute of an undefined variable.

9. Uncaught TypeError: Cannot set property

When accessing an undefined variable, it always returns undefined. We cannot get or set any undefined properties.

10. ReferenceError: event is not defined

This error is raised when a variable is undefined or is outside the current scope.

[Solved] vue Project Error: react lazy eslint error Parsing error: Unexpected token import

vue Project Error: react lazy eslint error Parsing error: Unexpected token import

1. You need to install the extension component eslint, and then click settings in settings – extension search – eslintrc and add this line (“parser”: “Babel-eslint”) in settings.json, save the code, and then run the project

[Solved] React Click the Event to Modify the State Value Error

React Click the Event to Modify the State Value Error

Make a mistake.

Cannot read properties of undefined (reading ‘setstate’) when updating the state value

import React from "react";
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello",
    };
    //Modify the codes behind this line
    
    //Modify the codes before this line
  }
  handleClick() {
    this.setState({
      text: "You clicked!",
    });
  }

  render() {
    return (
      <div>
        {/* Modify the codes behind this line */}
        <button onClick={this.handleClick}>Click Me</button>
        {/* Modify the codes before this line */}
        <h1>{this.state.text}</h1>
      </div>
    );
  }
}
export default MyComponent;

An error is reported when updating the state value,

Cannot read properties of undefined (reading ‘setState’)

It seems that the direction of this needs to be changed. I don’t quite understand it.

    // Modify the codes behind this line
    this.handleClick = this.handleClick.bind(this);
    // Modify the codes before this line

Value update after clicking

Another method is to modify it into an arrow function

  handleClick = () => {
    this.setState({
      text: "You clicked!",
    });
  };

The modified value can still be realized

React: How to Solve Web3 import error

How to Solve Web3 import error

Error Messages:
Solution:
Web3 and Create-react-app
If you are using create-react-app version >=5 you may run into issues building. This is because NodeJS polyfills are not included in the latest version of create-react-app.
Solution:
Install react-app-rewired and the missing modules
1. Down the Dependency below
yarn:
If you are using yarn:

yarn add --dev react-app-rewired process crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer

npm:
If you are using npm:

npm install --save-dev react-app-rewired crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer process

Create config-overrides.js in the root of your project folder with the content
2. Create config-overrides.js file in the main directory:

const webpack = require('webpack');

module.exports = function override(config) {
    const fallback = config.resolve.fallback || {};
    Object.assign(fallback, {
        "crypto": require.resolve("crypto-browserify"),
        "stream": require.resolve("stream-browserify"),
        "assert": require.resolve("assert"),
        "http": require.resolve("stream-http"),
        "https": require.resolve("https-browserify"),
        "os": require.resolve("os-browserify"),
        "url": require.resolve("url")
    })
    config.resolve.fallback = fallback;
    config.plugins = (config.plugins || []).concat([
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer']
        })
    ])
    return config;
}

3.Modify package.json
Within package.json change the scripts field for start, build and test. Instead of react-scripts replace it with react-app-rewired
before:
Before:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

After change:

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
},

4.Close the warning in the terminal
The missing Nodejs polyfills should be included now and your app should be functional with web3.
If you want to hide the warnings created by the console:
In config-overrides.js within the override function, add:
Add the following code in override method of config-overrides.js

config.ignoreWarnings = [/Failed to parse source map/];

The above contents are the processing methods on Web3 GIT

[Solved] react Chrome Browser Error: Uncaught TypeError: Cannot read properties of undefined (reading ‘forEach‘)

Error: Uncaught TypeError: Cannot read properties of undefined (reading ‘forEach’)

Cause: caused by the extension of Google browser

Solution 1: close the extension program of Google browser

Solution 2: find the wrong line and comment it out

Comment out the eighth line

Just restart

[Solved] react Error: Can‘t perform a React state update on an unmounted component

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indic

In the development of react, we may often encounter this warning:

Can't perform a React state update on an unmounted component.This is a no-op, but it indicates a memory leak in your application.

We cannot set state after the component is destroyed to prevent memory leakage

As for the above errors when switching routes in react, the actual reason is that after the component is mounted, you perform asynchronous operations, such as Ajax requests or setting timers, and you perform setstate operation in callback. When you switch routes, the component has been unmounted. At this time, the callback is still executing in the asynchronous operation, so the setstate does not get a value.

There are two solutions:

1. Clear all operations when uninstalling (e.g. abort your Ajax request or clear timer)

componentDidMount = () => {
    //1.ajax request
    $.ajax('Your request',{})
        .then(res => {
            this.setState({
                aa:true
            })
        })
        .catch(err => {})
    //2.timer
    timer = setTimeout(() => {
        //dosomething
    },1000)
}
componentWillUnMount = () => {
    //1.ajax request
    $.ajax.abort()
    //2.timer
    clearTimeout(timer)
}

2. Set a flag and reset it when unmount

componentDidMount = () => {
    this._isMounted = true;
    $.ajax('Your Request',{})
        .then(res => {
            if(this._isMounted){
                this.setState({
                    aa:true
                })
            }
        })
        .catch(err => {})
}
componentWillUnMount = () => {
    this._isMounted = false;
}

3. The simplest way (oil of gold)

componentDidMount = () => {
    $.ajax('Your Request',{})
    .then(res => {
        this.setState({
            data: datas,
        });
    })
    .catch(error => {
 
     });
}
componentWillUnmount = () => {
    this.setState = (state,callback)=>{
      return;
    };
}

CRA 5.0.0 Add Proxy Project Start Error [How to Solve]

Problem Description:
https://github.com/facebook/create-react-app/issues/11762#issue-1080972271
i.e.
Set the proxy in package.json, and then start the project through npm start or yarn start, the error is as follows:

>yarn start
yarn run v1.22.10
$ react-scripts start
Attempting to bind to HOST environment variable: test.localhost
If this was unintentional, check that you haven't mistakenly set it in your shell.
Learn more here: https://cra.link/advanced-config

Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
 - options.allowedHosts[0] should be a non-empty string.
error Command failed with exit code 1.

Solution: Don’t set the proxy in package.json, but set it in src/setupProxy.js, and delete the proxy in package.json, and finally restart npm start.

[Solved] react-router-dom Error: index.js:1 Warning: Functions are not valid as a React child.

index. js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of < Component /> from render. Or maybe you meant to call this function rather than return it.

reason:

1. When you return a component, you mistakenly write it as component instead of <Component/>

2. Maybe you want to call this function instead of return it.

For example:

① When calling a method, forget to add the following parentheses.

② When using react-router version 6.0.2 (released in 20211110), the writing method has been changed when registering the route.

[Solved] react-router-dom Error: <NavLink>activeClassName

Requirement: click the corresponding button to highlight

Error code:

Demo is the style class name corresponding to the highlight

<NavLink activeClassName="demo" className="list-group-item" to="/about">About</NavLink>
<NavLink activeClassName="demo" className="list-group-item" to="/home">Home</NavLink>

Error message:

It is said that react does not recognize the activeclassname attribute of the small hump writing method. It is recommended to change it to lowercase. After changing it to lowercase activeclassname, no error will be reported, but the style does not take effect.

Later, I found out that my react router DOM version is the latest version: 6.0 2:

In the new version, the active classname attribute is no longer used to highlight naclink. Instead, it is implemented directly in the classname as a callback function.

Change to the following code:

<NavLink className={({isActive}) => 'list-group-item' + (isActive ?' demo' : '')} to="/about">About</NavLink> 
<NavLink className={({isActive}) => 'list-group-item' + (isActive ?' demo' : '')} to="/home">Home</NavLink>

Note: a space should be added before “demo”. Otherwise, when clicking the button to trigger the active state, it will return to “list group itemdemo” (string splicing, if no space is added, the front and rear class names will be connected together), resulting in the ineffective CSS style.