- What I wish I knew when I started to work with react.js
- Originally written by David Yu
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: xionglong58
- Proofreader: Xujiujiu, WZnonstop
Since its initial release on May 29, 2013, React. Js has quickly taken over the Internet. It’s clear that many developers, myself included, have benefited from this amazing architecture.
There are plenty of react. js tutorials on Medium, and I wish one of them had given me the tips listed below when I first started learning React.js.
The.bind(this) operation is not required when using the arrow function
Usually, when you have a controlled component, your program will contain something like this:
class Foo extends React.Component{
constructor( props ){
super( props );
this.handleClick = this.handleClick.bind(this);
}
handleClick(event){
// your event handling logic
}
render() {return (
<button type="button"onClick={this.handleClick}> Click Me </button> ); }}Copy the code
You use.bind(this) for each method because most tutorials tell you to do that. When you have many controlled components, your constructor(){} can be particularly bloated.
Here’s what you can do:
class Foo extends React.Component{
handleClick = (event) => {
// your event handling logic
}
render() {return (
<button type="button"onClick={this.handleClick}> Click Me </button> ); }}Copy the code
Mine?
The arrow function in ES6 uses lexical scope to give methods access to this at their defined location.
When the service worker blocks your development
Service workers are good for progressive Web applications, enabling web pages to be accessed offline and optimized when the user’s network connection is poor.
However, if you don’t realize that the service worker is caching your static files, you will repeatedly try to do hot replace.
Only to find that the site has not been updated. 😰
Don’t panic, make sure your SRC /index.js file contains the following:
Service worker serviceworker.unregister ();Copy the code
As of version 16.8 of react.js, the top line is serverworker.unregister () by default.
However, if a later version changes, you will also know where to make the changes.
99% of the time you don’t need to use Eject
Create React App provides a command yarn eject that allows you to customize the build process of your project.
Remember when I tried to configure the build process myself in order to automatically embed SVG images in the code. I spent a lot of time understanding the build process. We ended up with an import file that injected SVG tags and improved the site’s load time by just 0.0001 milliseconds.
Eject Your React project is like opening the hood of a running car and changing the engine on the move.
Of course, if you’re a Webpack guru, it’s worth customizing the build process to meet the needs of your project.
If you just want to get things done on time, focus all your energy on what will propel you forward.
ESlint’s Auto Fix On Save will Save you a lot of time
You’ve probably copied poorly formed code from somewhere. Unable to accept its “ugly” format, you have to spend time manually adding Spaces and so on.
With ESLint and the Visual Studio Code plugin, the Code will automatically align when you save the file.
How do you set that up?
- In your
package.json
Add some dev dependencies to the file and execute the commandnpm i
或yarn
:
"devDependencies": {
"eslint-config-airbnb": "^ 17.1.0"."eslint-config-prettier": "^ 3.1.0"."eslint-plugin-import": "^ 2.14.0"."eslint-plugin-jsx-a11y": "^ 6.1.1." "."eslint-plugin-prettier": "^ 3.0.0"."eslint-plugin-react": "^ 7.11.0"
}
Copy the code
- Install the ESLint extension
- Select Auto Fix On Save
You do not need Redux, Styled – Components, etc
Every tool has a purpose, and it’s really good to know about different tools.
If you have a hammer in your hand, everything looks like a nail. — Abraham Maslow
When using some libraries you need to consider the time cost of introducing them and consider the following:
-
What problem am I going to solve?
-
Can the project benefit from the library in the long run?
-
Does React itself provide a ready-made solution?
Do you really need Redux when React has Context and Hooks?
I especially recommend Redux Offline when your users are in a bad network environment.
Reuse event handler
Reusing event handlers is a good option if you don’t like to write the same program over and over again:
class App extends Component {
constructor(props) {
super(props);
this.state = {
foo: "",
bar: ""}; } // Reusablefor all inputs
onChange = e => {
const {
target: { value, name },
} = e;
// name will be the state name
this.setState({
[name]: value
});
};
render() {
return (
<div>
<input name="foo" onChange={this.onChange} />
<input name="bar"onChange={this.onChange} /> </div> ); }}Copy the code
The setState method is asynchronous
When I was young, I might have written the following routine:
constructor(props) {
super(props);
this.state = {
isFiltered: false}; } toggleFilter = () => { this.setState({ isFiltered: ! this.state.isFiltered }); this.filterData(); }; FilterData = () => {// this.state.isFiltered should betrueBut in fact it isfalse
if (this.state.isFiltered) {
// Do some filtering
}
};
Copy the code
Suggestion 1: Pass state down
toggleFilter = () => { const currentFilterState = ! this.state.isFiltered; this.setState({ isFiltered: currentFilterState }); this.filterData(currentFilterState); }; filterData = (currentFilterState) => {if(currentFilterState) {// Do some filtering}};Copy the code
Suggestion 2: Operate state in the second callback of setState
toggleFilter = () => { this.setState((prevState) => ({ isFiltered: ! prevState.isFiltered }), () => { this.filterData(); }); }; filterData = () => {if(this.state.isFiltered) {// Do some filtering}};Copy the code
conclusion
These tips saved me a lot of time, and I’m sure there are plenty of other tips for react.js. Feel free to comment in the comments section and share tips you know.
(Commercial break) If you want to integrate your website with the wechat platform and get more than 1 billion users, sign up to get a glossary of commonly used wechat terms.
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.