Let’s first be clear that this is not a post with all the best coding practices in React. It’s a post about some of the practices that I have learned over years of my experience while working with React. They might not be the best ones, but they surely add quality to the code written.
首先让我们清楚一点,这不是关于React中所有最佳编码实践的文章。 这是一篇有关我在使用React的过程中多年积累的经验的文章。 它们可能不是最好的,但是肯定会增加所编写代码的质量。
确定组件类型-功能还是经典? (Deciding the component type — functional or classical?)
With the introduction of hooks in React, I often find people struggling over the point where they cannot decide whether they should create a functional component or classical component? If you are not familiar with Hooks yet, then you check this.
随着React中钩子的引入,我经常发现人们在无法决定应该创建功能组件还是经典组件的问题上苦苦挣扎。 如果您还不熟悉Hooks,请选中 此项 。
This depends completely on your requirement — if your component has fewer or no states with not much involvement of component lifecycle methods, then you can choose to create a functional component else you can choose a normal classical component. There are no strict rules to make this decision.
这完全取决于您的需求-如果您的组件状态少或没有,而组件生命周期方法的参与度不高,则可以选择创建功能组件,也可以选择常规的经典组件。 没有严格的规则可以做出此决定。
在组件中组织代码 (Organising code in component)
This is strictly a personal choice I feel, one can follow any standard way to write code in their component. The main idea here is to follow a consistent approach for writing code in all components.
我认为,这完全是个人选择,可以遵循任何标准方法在其组件中编写代码。 这里的主要思想是遵循一致的方法在所有组件中编写代码。
It’s not what we do once in a while that shapes our lives. It’s what we do consistently. — Anthony Robbins
并不是我们偶尔做的事情会影响我们的生活。 这就是我们一贯所做的。 -安东尼·罗宾斯
整理进口商品 (Organising your imports)
One can follow any standard order to manage their imports in the component, I have listed the import sequence order which I follow for managing imports in my components:
可以遵循任何标准顺序来管理它们在组件中的导入,我列出了遵循的导入顺序顺序,用于管理组件中的导入:
Imports from ‘react’ or ‘react-dom’
从“ react ”或“ react-dom ”导入
3rd party library imports like ‘lodash’ or ‘clsx’
第三方库导入,例如“ lodash ”或“ clsx ”
- Import of components from my ‘ui-kit’ 从我的“ ui-kit”导入组件
- Import context providers 导入上下文提供者
- Import of utility methods, helper classes and constants 导入实用程序方法,助手类和常量
- Import of scss/css files 导入scss / css文件
import React, { useState } from 'react'; import clsx from 'clsx';
import * as _ from 'lodash'; import Button from 'ui-kit/Button';import { AppContext } from './App.js'; import { CONSTANTS } from "./utility/constants";
import { convertToJSON } from './utility/helper'; import './scss/app.scss';
组织组件状态和变量 (Organising component state and variables)
In classical components we define state variables for the component in the constructor and in functional components we define them at the beginning of the functional component. It is the standard way but we can take care of some additional points while doing that:
在经典组件中,我们在构造函数中为组件定义状态变量,而在功能组件中,我们在功能组件的开头定义它们。 这是标准方法,但是我们可以在此过程中注意一些其他事项:
- Organise all state variables based on their value types 根据其值类型组织所有状态变量
- Define context consumer variables 定义上下文使用者变量
- Define refs 定义参考
- Other local variables 其他局部变量
const [isActive, setIsActive] = useState(false);
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [isScreenLoading, setIsScreenLoading] = useState(true);
const [selectedIndex, setSelectedIndex] = useState(-1);
const [message, setMessage] = useState("Hello World!");
const [rows, setRows] = useState([]);const appContext = useContext(AppContext);const buttonRef = useRef(null);
const inputRef = useRef(null);const pathID = props.match.params.id;
组件中的组织方法 (Organising methods in component)
Everybody follows different techniques for managing methods in their component. But we can surely follow some conventions to make our component code easily understandable to any developer.
每个人都遵循不同的技术来管理其组件中的方法。 但是我们可以肯定遵循一些约定,以使我们的组件代码易于被任何开发人员理解。
- Define all the API call invocation methods 定义所有API调用方法
- Define all event handlers like button click, text change, error handlers etc 定义所有事件处理程序,例如按钮单击,文本更改,错误处理程序等
- Define helper methods returning either JSX or data required for render 定义返回JSX或渲染所需数据的助手方法
- Define lifecycle methods like componentDidMount() or hooks like useEffect 定义生命周期方法,例如componentDidMount()或钩子,例如useEffect
const fetchInitialData = (bot, channel) => {
const endpoint = `/v1/todos`;
const headers = {
"Accept": "application/json",
"Content-type": "application/json"
};
fetch(endpoint, headers).then(response => response.json()).then(response => setRows(response.data));
}const statusChangeHandler = (status) => {
setIsActive(status);
}const customScroll = (event) => {
// custom scroll listener
}const getPopupMessage = () => {
return `This message is received from user ${pathID}`;
}useEffect(() => {
// register listener
window.addEventListener("scroll", customScroll); return () => {
// unregister listener
window.removeEventListener("scroll", customScroll);
}
}, []);
These are some of the practices that I follow to make the code in all my components consistent. As people say, there is no such thing as “perfect” code, there is always a chance for “better” code. Learn to code better everyday! Happy Coding!
这些是我为了使所有组件中的代码一致而遵循的一些实践。 正如人们所说,没有“完美”的代码,总有机会获得“更好”的代码。 每天学习更好的编码!code编码愉快!
翻译自: https://medium.com/swlh/coding-practices-in-react-cdadd60ba15