Home > Web Front-end > JS Tutorial > body text

Detailed explanation of methods for store optimization of React components

小云云
Release: 2018-01-20 17:32:27
Original
1431 people have browsed it

This article mainly introduces the method of using store to optimize React components. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

When writing components using React, we often encounter situations where two different components need to share state, and the usual approach is to promote the state to the parent component. But there is a problem with this, that is, although only two components need this state, because the state is mentioned to the parent component, when the state changes, the parent component and all sub-components below it will be re-rendered. If your The parent component is relatively complex and may cause performance problems if it contains many other sub-components.

Redux puts the state in the global store, and then the components subscribe to the state they need. When the state changes, only those components whose subscribed state changes will be re-rendered, thus avoiding The side effects of the improved status mentioned above. However, when we are writing a React component library, the combination of redux and react-redux may be a bit too heavy. So we can write a simple store ourselves to implement a subscription model similar to Redux.

Refer to the implementation of Redux to write a simplified version of createStore:


function createStore(initialState) {
 let state = initialState;
 const listeners = [];

 function setState(partial) {
  state = {
   ...state,
   ...partial,
  };
  for (let i = 0; i < listeners.length; i++) {
   listeners[i]();
  }
 }

 function getState() {
  return state;
 }

 function subscribe(listener) {
  listeners.push(listener);

  return function unsubscribe() {
   const index = listeners.indexOf(listener);
   listeners.splice(index, 1);
  };
 }

 return {
  setState,
  getState,
  subscribe,
 };
}
Copy after login

Our createStore is very simple. There are only 33 lines including blank lines, and the total is exposed There are 3 methods. There is no dispatch and reducer in Redux. The state is changed directly through the setState method. Let's use it as an example of a counter.


class Counter extends React.Component {
 constructor(props) {
  super(props);

  // 初始化 store
  this.store = createStore({
   count: 0,
  });
 }

 render() {
  return (
   <p>
    <Buttons store={store} />
    <Result store={store} />
   </p>
  )
 }
}

class Buttons extends React.Component {
 handleClick = (step) => () => {
  const { store } = this.props;
  const { count } = store.getState();
  store.setState({ count: count + step });
 }

 render() {
  return (
   <p>
    <button onClick={this.handleClick(1)}>+</button>
    <button onClick={this.handleClick(1)}>-</button>
   </p>
  );
 }
}

class Result extends React.Component {
 constructor(props) {
  super(props);

  this.state = {
   count: props.store.getState().count,
  };
 }

 componentDidMount() {
  this.props.store.subscribe(() => {
   const { count } = this.props.store.getState();
   if (count !== this.state.count) {
    this.setState({ count });
   }
  });
 }

 render() {
  return (
   <p>{this.state.count}</p>
  );
 };
}
Copy after login

In the example, changing the state in the store through store.setState in Buttons will not cause the entire Counter to be re-rendered, but because the Result is subscribed to the store changes , so when the count changes, you can re-render by changing the state in your component, thus cleverly avoiding unnecessary rendering.

Finally, although the above createStore only has a few dozen lines of code, I still wrote it into a library called mini-store and put it on GitHub, and provided a Redux-like Provider and connect method, which adds up to Just over 100 lines of code. If you are also writing a React component library and need to manage the state of a complex component, you might as well try this optimization method.

Related recommendations:

How to use the Props of the parent component "outside" the React component

The life cycle of the React component What is a function

An example tutorial on communication between React components

The above is the detailed content of Detailed explanation of methods for store optimization of React components. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!