React is a very popular front-end framework. Today we explore seven points that React developers should pay attention to. 1. Component bloatReact developers don’t create enough components as necessary. This problem is not limited to React developers, but also affects many Vue developers. Of course, we are talking about React now. In React, we can create a component with a lot of content to perform our various tasks, but it is best to keep the components concise - one component is associated with one function. This not only saves your time, but also helps you locate the problem well. // ./components/TodoList.js import React from 'react'; import { useTodoList } from '../hooks/useTodoList'; import { useQuery } from '../hooks/useQuery'; import TodoItem from './TodoItem'; import NewTodo from './NewTodo'; const TodoList = () => { const { getQuery, setQuery } = useQuery(); const todos = useTodoList(); return ( <div> <ul> {todos.map(({ id, title, completed }) => ( <TodoItem key={id} id={id} title={title} completed={completed} /> ))} <NewTodo /> </ul> <div> Highlight Query for incomplete items: <input value={getQuery()} onChange={e => setQuery(e.target.value)} /> </div> </div> ); }; export default TodoList; 2. Change the state directly In React, state is supposed to be immutable. If you modify the state directly, it will cause performance problems that are difficult to fix. const modifyPetsList = (element, id) => { petsList[id].checked = element.target.checked; setPetsList(petList) } In the above example, you want to change the checked key in the array object. But you have a problem: because the object was changed using the same reference, React can't observe that and trigger a re-render. To solve this problem, we should use the setState() method or the useState() hook. We rewrite the previous example using the useState() method. const modifyPetsList = (element, id) => { const { checked } = element.target; setpetsList((pets) => { return pets.map((pet, index) => { if (id === index) { pet = { ...pet, checked }; } return pet; }); }); }; 3. The props should pass a numeric value but a string is passed, and vice versa This is a very minor error and should not occur. class Arrival extends React.Component { render() { return ( <h1> Hi! You arrived {this.props.position === 1 ? "first!" : "last!"} . </h1> ); } } Here === is invalid for the string '1'. To solve this problem, we need to wrap it with {} when passing props values. // ❌ const element = <Arrival position='1' />; //✅ const element = <Arrival position={1} />; 4. Key is not used in list component Suppose we need to render the following list items: const lists = ['cat', 'dog', 'fish']; render() { return ( <ul> {lists.map(listNo => <li>{listNo}</li>)} </ul> ); } Of course, the above code works. When the list is large and needs to be modified, it will cause rendering problems. React keeps track of all list elements on the Document Object Model (DOM). There is no record to tell React what happened to the list. To solve this problem, you need to add keys to your list elements. Keys give each element a unique identity, which helps React determine which items have been added, removed, or modified. <ul> {lists.map(listNo => <li key={listNo}>{listNo}</li>)} </ul> 5. setState is an asynchronous operation It's easy to forget that state in React operates asynchronously. If you try to access a value right after setting it, you might not be able to get the value right away. handlePetsUpdate = (petCount) => { this.setState({ petCount }); this.props.callback(this.state.petCount); // Old value }; You can use the second parameter of setState(), the callback function to handle it. for example: handlePetsUpdate = (petCount) => { this.setState({ petCount }, () => { this.props.callback(this.state.petCount); // Updated value }); }; 6. Frequent use of Redux In large React apps, many developers use Redux to manage global state. 7. Component names do not begin with a capital letter In JSX, components that start with lowercase will be compiled down to HTML elements. So we should avoid the following: class demoComponentName extends React.Component { } This will result in an error: If you want to render a React component, it needs to start with a capital letter. class DemoComponentName extends React.Component { } Afterword The above content is extracted from Top 10 mistakes to avoid when using React. It uses a paraphrase approach to extract 7 more practical contents. This concludes this article about 7 cases of avoiding pitfalls when using react. For more relevant react pitfalls, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Add crontab scheduled tasks to debian docker container
>>: MySQL 8.0.12 winx64 decompression version installation graphic tutorial
Table of contents 1. Installation 1. Introduction...
1. Add the isolation marker: ip netns add fd 2. P...
Table of contents Partitioning mechanism SELECT q...
Table of contents step 1. Configure routing rules...
Download the installation package from the offici...
Table of contents Update the image from an existi...
Table of contents 1. Anti-shake function 2. Use d...
Problem description: When inserting Chinese chara...
Preface To solve the single point of failure, we ...
nginx server nginx is an excellent web server tha...
aforementioned This article is very short~ The ma...
Table of contents 1 Introduction to nginx 1 What ...
<br />Original address: http://andymao.com/a...
1. Background In actual projects, we will encount...
To achieve the following goals: Mysql database wi...