preface
React this is an article that explains React in a comprehensive way. There are a lot of basic knowledge in it that you can learn while looking it up. In this paper, starting from the most common view in business development, loading effect is different from implementation, and the present front-end development should be considered in business.
Entry level Operation
State
In the simplest implementation, we declare a state inside the Loading component, and judge the display of the Loading effect through the code logic.
export default class extends Component {
...
render() {
return this.state.loading ? <div className="loader"/> : <div>finish</div>; }}Copy the code
Complete demo
Props
With the development of business, this Loading component will be used in many places. The code above is coupled with a lot of logic. In order to make this component reusable, we can extract the business logic of the component and improve its internal state, so this component is a UI component that can be reused.
export default function(props) {
return props.loading ? <div className="loader" /> : <div>finish</div>;
}
Copy the code
Complete demo
Note: You may be wondering why Func and Class can both implement a component, and what is the difference between them? React does a lot of different things. If it’s a Class, React instantiates it with the new keyword and calls the Render method. If it’s a Func function, React calls it directly.
Refs
React provides Refs that allow you to access DOM nodes or React elements.
export default class extends Component {
componentDidMount() {
fetch().then(() => {
this.el.changeLoading(false);
});
}
render() {
return( <Loading ref={el => { this.el = el; }} / >); }}Copy the code
Complete demo
General logic pull away
When your application gets to a certain level of complexity, different pages will have loading effects, and you don’t want to write the same logic repeatedly on every page. This will cause your code to be repetitive and confusing.
There are two common solutions in React, HOC and Render Props. In fact, neither of these two concepts depends on React.
Forget React for a moment, let me write two examples of HOC and Render Props, and you’ll see how easy component reuse is.
HOC
HOC is essentially a decorator pattern that takes a component as an argument and returns the same component so you can add some extra functionality.
const func = () => {
console.log("func");
};
const wrap = func => {
console.log("wrap");
returnfunc; }; // wrap(func)();Copy the code
Complete demo
Render Props
Render Props means that we pass a callback function as a parameter to perform any operation using the result of the Render function.
const func = param => {
console.log("func");
};
const wrap = (param, func) => {
console.log("wrap"); func(param); }; // wrap logic is already used."", func);
Copy the code
Complete demo
Similarities:
- Both can help us very well
Reuse component logic
; - Similar to the callback function, when the number of nested layers is too high, causes
The callback hell
.
Difference:
- HOC and the parent component have the same attribute name, attribute passing will cause attribute loss;
- Render Props you only need to instantiate a middle class, HOC you need to instantiate an extra middle class every time you call a place.
In general, I personally prefer the Render Props approach when it comes to reusing component logic.
Complex state management
As your application grows larger and components interact more and more complex, the data logic of the entire page becomes difficult to manage. In this case, you can choose some state management tools such as Redux, Flux, dVA, etc.
Redux
I don’t really want to talk about these data flow frameworks because their concepts of Action, Store, and Dispatch are too obscure to understand. Modern front-end frameworks React and Vue are essentially the same thing: try to render data, then operate on the view to update data, re-render the view, and refresh the page. The data is called store, the action is called ation, the triggering action is called dispatch, and the rendering of the data to the view is handled by React/Vue.
(Image from here)
// reducers.js
const initialState = {
loading: false
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case "CHANGE_LOADING":
return {
loading: action.payload
};
default:
returnstate; }}Copy the code
Complete demo
Saga
When you have a lot of asynchronous operations in your code, such as fetch requests, you definitely think of event listeners, callback functions, publish/subscribe. Ok, so the previous example is actually the event listening approach, and the dominant solution for callback functions is redux-thunk, and the dominant solution for publish/subscribe is saga.
import { takeLatest, put } from "redux-saga/effects";
import fetch from "./fetch";
function* fetchInfo(action) {
yield put({
type: "CHANGE_LOADING",
payload: true
});
yield fetch();
yield put({
type: "CHANGE_LOADING",
payload: false
});
}
export default function* fetchSaga() {
yield takeLatest("FETCH_REQUEST", fetchInfo);
}
Copy the code
Complete demo
When you see React patiently, I know you must have some experience with React. Now you can do many things, such as raising the loading state to the top of the Store. Then there is only one loading state in the whole site. Then you can encapsulate fetch with a HOC to modify the loading state, which is a relatively perfect loading. In fact, React business development can use this routine.
The new API
Context
For simple businesses with many pages and a complex nesting hierarchy, you can certainly not use state management tools. You can try using Context, which makes it easy to pass data, which is an implementation of Render Props.
export default React.createContext({
loading: false,
changeLoading: () => {}
});
Copy the code
Complete demo
Hooks
Here, calm down. Did you do something wrong?
My business just wanted to write a simple loading effect, but learned a lot about component life cycles.
Hooks allow you to convert lifecycle oriented programming into business logic oriented programming by using the React function function by performing a single function call.
import React, { useState, useEffect } from "react";
import Loading from "./Loading/index";
import fetch from "./fetch";
function App() {
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch().then(() => {
setLoading(false); }); } []);return <Loading loading={loading} />;
}
export default App;
Copy the code
Complete demo
Sum it up
Each of these points is implemented, but they are not isolated. You can summarize and abstract your own methodology based on your cognitive and business characteristics.
More understanding, more abstract, more thinking, practice eighteen kinds of martial arts, when you meet problems to play with ease;
React now advertises more and more things, so it’s best to learn about them first, then be critical and rational, and prevent yourself from refactoring your own code with new features every day.
Refer to the article
The React website
When do I know I’m ready for Redux?
The article can be reproduced at will, but please keep this link to the original text.
Please send your resume to caijun. HCJ (at)alibaba-inc.com.