Tag Archives: front end

[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

[Solved] Vue eslint Error: Component name “*****“ should always be multi-word

Vue eslint Error: error “Component name “*****“ should always be multi-word”

Problems:

In the project created by Vue-cli, after the file is created and named, an error will be reported as “component name” ***** “should always be multi-word”;

The screenshot of error reporting is as follows:

Component name "******" should always be multi-word.eslintvue/multi-word-component-names

Reasons for error reporting:

The naming of components is not standardized. According to the official style guide of eslint, in addition to the root component (app.vue), the user-defined group

The part name should be composed of multiple words (using the naming method of big hump or connecting words with “-“) to prevent conflict with HTML tags;

 

The project created by the latest vue-cli uses the latest vue/cli-plugin-eslint plugin, which references the vue/multi-word-component-names rule after vue/cli-plugin-eslint v7.20.0.

The vue/multi-word-component-names rule has been referenced since vue/cli-plugin-eslint v7.20.0, so this error was determined at compile time.

Solution:

Scheme 1: Rename (valid for personal test)

Rename the name of the file

Modify the component name to multiple words, use hump naming method or connect words with “-“.

So the problem is solved~~~~

Examples are as follows:

Scheme 2: configure Vue config.js file (online method, invalid for my use)

Find vue.com in the root directory config. JS file (if not, create a new one), and add the following code in Vue config. JS file, add the following code

lintOnSave: false // Close eslint verification

Examples are as follows:

This scheme only does not report errors during compilation. If vscode + eslint is used, a red prompt will be marked in the file header, and the official does not recommend turning off the verification directly;

Configure Vue config. The method of JS file (scheme 2) generally can not solve the problem, so it is not recommended to use it

If you find that you haven’t solved the problem, you might as well try other solutions

Method 3: configuration eslintrc.js file (valid for personal test)

1. Turn off naming rules

Find it eslintrc.js file and adds such a sentence in rules

'vue/multi-word-component-names': "off" // Close name verification

It is suggested to use this method, which is more correct and reasonable;

Examples are as follows:

It is found that there is no error, and it can run normally ~ ~ ~

The above is to close the naming rules, and the component name will not be verified. The official recommended setting is to ignore the component name

2. Ignore individual component names

// Add component naming ignore rule
    "vue/multi-word-component-names": ["error",{
       "ignores": ["Home", "User"]//Component names to ignore
    }]

Recommended scheme 3, highly recommended!!!

For example:

Scheme 4:

The third scheme is to close and ignore the rule of component name; Ignore by component name

The fourth scheme is the closing rule according to the file.

Close a file naming rule verification

Found in the root directory eslintrc. JS file, (if not, create a new one (note that there is a point in front of the file))

Add the following code to the overrides of the file:

{  
 files: ['src/views/index.vue','src/views/**/index.vue'],   // Match index.vue in views and secondary directories
 rules: {
 'vue/multi-word-component-names': "off",
 } // assign rules to the files matched above
}

Where files: [] is used to match files, and the * sign represents all files. index. Vue can also be changed to * Vue, which is all Vue files in the matching directory

Document content:

module.exports = {
  root: true,
  env: {
    node: true
  },
  'extends': [
    'plugin:vue/essential',
    'eslint:recommended'
  ],
  parserOptions: {
    parser: '@babel/eslint-parser'
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ?'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ?'warn' : 'off',
  },
  overrides: [
        //Here is the code added
        { 
          files: ['src/views/index.vue','src/views/**/index.vue'], // match index.vue in views and secondary directories
          rules: {
          'vue/multi-word-component-names': "off",
          } // Assign rules to the files matched above
        },
    {
      files: [
        '**/__tests__/*.{j,t}s?(x)',
        '**/tests/unit/**/*.spec.{j,t}s?(x)'
      ],
      env: {
        jest: true
      }
    }
  ]
}

Four schemes I suggest using scheme 3 and scheme 4. I don’t recommend using the method of scheme 2, which is common on the Internet. It’s not easy to use!

Very important notes: (the configuration file will take effect only after the project is restarted)

In a running project, to modify the configuration file, you must first delete the project in the terminal and click Ctrl + C twice to terminate the project, and then NPM run serve to re run the project. The modified configuration file can take effect

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] VUE3 Error: Error: ENOSPC: System limit for number of file watchers reached

(env) [root@VM-20-16-centos vue_test2]# npm run serve

> [email protected] serve
> vue-cli-service serve

 INFO  Starting development server...
[10%] building (0/0 modules)
node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error: ENOSPC: System limit for number of file watchers reached, watch '/root/work/vue3/vue_test2/public'
    at FSWatcher.<computed> (node:internal/fs/watchers:244:19)
    at Object.watch (node:fs:2251:34)
    at createFsWatchInstance (/root/work/vue3/vue_test2/node_modules/chokidar/lib/nodefs-handler.js:119:15)
    at setFsWatchListener (/root/work/vue3/vue_test2/node_modules/chokidar/lib/nodefs-handler.js:166:15)
    at NodeFsHandler._watchWithNodeFs (/root/work/vue3/vue_test2/node_modules/chokidar/lib/nodefs-handler.js:331:14)
    at NodeFsHandler._handleDir (/root/work/vue3/vue_test2/node_modules/chokidar/lib/nodefs-handler.js:567:19)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async NodeFsHandler._addToNodeFs (/root/work/vue3/vue_test2/node_modules/chokidar/lib/nodefs-handler.js:617:16)
    at async /root/work/vue3/vue_test2/node_modules/chokidar/index.js:451:21
    at async Promise.all (index 0)
Emitted 'error' event on FSWatcher instance at:
    at FSWatcher._handleError (/root/work/vue3/vue_test2/node_modules/chokidar/index.js:647:10)
    at NodeFsHandler._addToNodeFs (/root/work/vue3/vue_test2/node_modules/chokidar/lib/nodefs-handler.js:645:18)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async /root/work/vue3/vue_test2/node_modules/chokidar/index.js:451:21
    at async Promise.all (index 0) {
  errno: -28,
  syscall: 'watch',
  code: 'ENOSPC',
  path: '/root/work/vue3/vue_test2/public',
  filename: '/root/work/vue3/vue_test2/public'
}

Solution:

Execute the following command

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

[Solved] Vue Project Error: Module build failed: Error: Missing binding

Train of thought

Through the error message, we can see that the core problem is that the sass file cannot be found in the dependent file. This prompts us to reinstall sass

1. Switch to the dependent folder of the current project through CD, that is, node_modules file, and then run the command to install sass. The command is as follows

npm rebuild node-sass

2 . Then switch to the project folder and run the command to update it. The command is as follows:

npm update

3. Finally, run the command to start the project

npm run dev

[Solved] SyntaxError: E:\IdeaProject\src\main.js: Identifier ‘ElementPlus‘ has already been declared

Problems encountered

 

Module build failed (from .de_modules/babel-loaderb/index.js):
SyntaxError: E:\IdeaProjects\![Please add image description](https://img-blog.csdnimg.cn/c9d36e8ab6984fc390345ad4d7129c70.png)
springboot_vue\src\main.js: Identifier 'ElementPlus' has already been declared. (8:7)


Solution:
by checking the project source code, it is found that the reason for this error is that elementplus has been imported twice. The solution is to delete one!

The effects after the solution are as follows:


Summary

As a back-end R & D personnel, I think it is necessary to have a little understanding of the front-end. Although I may not take the road of R & D in the future, I feel that with the existence of the epidemic, the reduction of Posts and the improvement of academic qualifications, the internal volume may become more and more serious, and the iron still needs to be hard! Choose a road and stick to it. At least the result won’t be too bad. Come on~

[Solved] ESLint: Parsing error: Unexpected token(prettier/prettier)

eslint HTML file error after introducing prettier: parsing error: unexpected token (prettier/prettier)

Cause of problem

The parser of prettier is not configured correctly. (I don’t know why it needs to be configured separately. It should have default configuration for all corresponding file types)

Solution

Modify .prettierrc.json , add overides , and configure the parser of HTML. Configurable item: Reference

{
  "printWidth": 120,
  "singleQuote": true,
  "bracketSpacing": true,
  "jsxBracketSameLine": true,
  "htmlWhitespaceSensitivity": "ignore",
  "overrides": [
    {
      "files": "*.html",
      "options": {
        "parser": "html"
      }
    }
  ]
}

How to Solve Error: [Vue warn]: Missing required prop: “value”

I Error reporting scenario

This error occurs when using the El-select component of element-UI in Vue

Operation results: (the following errors will be reported when the interface is initially loaded, and will continue to be reported when clicking El-select and switching El-option)

[Vue warn]: Missing required prop: "value"  

II Error reporting reason

2.1. There is no bidirectional data binding (V-model) in El-select

2.2 El-option does not assign value

You can also try to check errors like these!

[Solved] Errors: 1 http://eslint.org/docs/rules/quotes…elementUI Import Error

Introduction of elementui

Add the following in main.js of src:

import Element from 'element-ui'
import "element-ui/lib/theme-chalk/index.css"
Vue.use(Element)

Introduce error reporting

Errors:
  1  http://eslint.org/docs/rules/quotes

You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.

Solution:

In the build/webpack.base.conf.js file, comment out or remove the rule about eslint in: module->rules

Then re-execute the command: npm run dev

It’s normal

[Solved] JSON.parse() Error: Unexpected end of JSON input

Error returned during JSON.parse() conversion due to conversion characters or other special characters in the data of the converted JSON.stringify().

Solution:

encoding before the JSON.stringify() transformation and decoding the operation when JSON.parse() is solved.

Example:

Jump pass parameter

 toEdit() {
    this.data.userInfo.faceData = this.data.faceData
    let info = encodeURIComponent(JSON.stringify(this.data.userInfo))
    wx.navigateTo({
      url: '../userEdit/userEdit?info=' + info 
    })
  },

receive data

onLoad(options) {
	//decodeURIComponent decoding
   let info = JSON.parse(decodeURIComponent(options.info))
   this.setData({info:info})
}