Tag Archives: react.js

[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.

React project is packaged and set as required Error [How to Solve]

./node_modules/antd/es/style/index.less (./node_modules/css-loader/dist/cjs.js??ref–6-oneOf-7-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref–6-oneOf-
7-3!./node_modules/less-loader/dist/cjs.js??ref–6-oneOf-7-4!./node_modules/antd/es/style/index.less)
ValidationError: Invalid options object. Less Loader has been initialized using an options object that does not match the API schema.

This is the problem with the less-loader version

yarn remove less-loader
yarn add [email protected]

How to Solve React devtools plug-in Error

The developer debugging tool plug-in of react will prompt an error in chrome after installation:

react-refresh-runtime.development.js:465

Solution:

Under the react project (not the plug-in file directory), find \node_Modules\@pmmmwh\react refresh webpack plugin\client

Reactrrefreshentry.js file, comment out this line:

//RefreshRuntime.injectIntoGlobalHook(safeThis);

Error in value transmission of react parent-child component

Scenario:

Call subcomponent  

1) Analyze the problem:

Type ‘XXX’ is not assignable to type ‘Omit< WrappedComponentProps< any>, “intl”>’.

There seems to be a problem with the type of subcomponents, which is related to Intl internationalization. Remove the internationalization and routing of subcomponents

2) It will still report errors:  

Type ‘{pagevalue: pagevalue_type | undefined;}’ does not have the same attributes as type ‘internalattributes & amp; {children?: reactnode;}’. ts(2559)

  resolvent:

As shown in the figure above, you need to add a generic & lt; to the type react.fc of the solution component; any>

Here the problem is solved

[Solved] IE Browser Error: unhandled promise rejection error: access is denied. File stream Download

There are many export files and download files in the project. The front end adopts the file stream download method, requests the back-end interface and returns the file stream
at first, it was not clear that the ordinary dynamic creation a tag method was not compatible with ie. later, the bug “unhandled promise rejection error: access denied” appeared in the test on ie. after seeing this problem, it was directly copied to Baidu, and then the result was that the promise method might be wrong. After changing all the promise methods, an error was reported, Later, I thought about whether the way to create a tag was not compatible with ie, and Baidu adopted the method of downloading file stream compatible with ie. sure enough, I got the following solution and recorded it.

IE browser has Microsoft’s own mssaveblob method. The download of a tag is not compatible with ie.

//Since the method is used in several places in the page, it is wrapped as a component
// Don't forget to set the responseType='blob' in the request header, the react project is already encapsulated in the request
export const exportSaveData = (data, filename) => {
    let blob = new Blob([data], { type: 'application/x-www-form-urlencoded' });
    let blobUrl = window.URL.createObjectURL(blob);
    if (window.navigator.msSaveBlob) { // determine if the method is available for Internet Explorer
        try {
            window.navigator.msSaveBlob(blob, filename)
        } catch (e) {
            console.log(e);
        }
    } else {
        // Google Chrome Create a tag Add download attribute to download
        const aElement = document.createElement('a'); // create a tag dynamically
        document.body.appendChild(aElement); // append the created a tag to the body
        aElement.style.display = 'none'; //you can set the a tag not to be visible
        aElement.href = blobUrl; a tag's href is the processed blob
        aElement.download = filename;
        aElement.click();
        document.body.removeChild(aElement);
        window.URL.revokeObjectURL(blobUrl); //release the blob object
    }
}

Perfectly solve the problem that IE cannot export

Error: EPERM: operation not permitted, mkdir ‘D:\nodejs\node_modules\npm\node_cache\_npx‘

Question:

  implement   NPX create react app XXX reports an error

PS D:\Desktop>npx create-react-app demo
Error: EPERM: operation not permitted, mkdir 'D:\nodejs\node_modules\npm\node_cache\_npx'
TypeError: Cannot read property 'get' of undefined
    at errorHandler (D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\utils\error-handler.js:213:18)
    at D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\bin\npm-cli.js:83:20
    at cb (D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\npm.js:215:22)
    at D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\npm.js:253:24
    at D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\config\core.js:81:7
    at Array.forEach (<anonymous>)
    at D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\config\core.js:80:13
    at f (D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\config\core.js:178:20)
    at D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\node_modules\mkdirp\index.js:35:29
D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\utils\error-handler.js:213
  if (npm.config.get('json')) {
                 ^

TypeError: Cannot read property 'get' of undefined
    at process.errorHandler (D:\nodejs\node_modules\npm\node_global\node_modules\npx\node_modules\npm\lib\utils\error-handler.js:213:18)
    at process.emit (events.js:400:28)
    at process._fatalException (internal/process/execution.js:167:25)
Install for [ 'create-react-app@latest' ] failed with code 7

terms of settlement:

Create react- app@latest Install to global

npm install create-react-app@latest -g

Run after installation

 npx create-react-app demo

So you can write the project