Plusieurs façons d'optimiser une application React-Redux

Il semblerait pourquoi parler de Redux en 2020. Après tout, il y a tellement de grandes alternatives dans le domaine des directeurs d'État ( par exemple ). Après tout, il y a une douzaine de raisons de ne pas aimer Redux, sur lequel de nombreux articles ont été écrits et de nombreux rapports ont été rédigés. Cependant, quelque chose ne peut pas lui être retiré - vous pouvez y écrire un grand site Web fonctionnel, pris en charge et rapide . Ci-dessous, je parlerai des techniques qui aident à faire cela en utilisant react-redux. Intéressant? Bienvenue au chat.


Optimiser l'application redux


Avertissement Pour une personne qui a lu attentivement la documentation, la couverture ne se cassera pas. Votre capitaine.


Personnellement, j'adore Redux. Pour la simplicité et le minimalisme. La bibliothèque ne fait pas de magie. Là où il n'y a pas de magie, il n'y a aucun moyen de casser accidentellement quelque chose, sans savoir ce que vous avez cassé. Le contrôle revient aux mains du programmeur, qui, d'une part, libère les mains, et d'autre part, nécessite une compréhension lors de son utilisation. La discussion ci-dessous se concentrera sur une telle utilisation de la «compréhension» - des techniques qui, dans le premier couple, nécessitent de la conscience et de la discipline, mais elles sont alors perçues comme quelque chose de naturel.


À propos du magasin et de l'état


Brièvement sur ces deux concepts, pour qu'il n'y ait pas de confusion.


Store redux — , state , state, state, - . ""


State redux-store , , , , , . State . ""


mapStateToProps


connect, , HOC-, store . connect mapStateToProps. mapStateToProps . mapStateToProps ( , ).


1 mapStateToProps.

,


const mapStateToProps = () => {
  return {
    units: [1, 2, 3]
  }
}


const UNITS = [1, 2, 3];

const mapStateToProps = () => {
  return {
    units: UNITS
  }
}

, react-redux , . mapStateToProps . mapStateToProps shallowEqual ( ). .. , , .


, [1, 2, 3], shallowEqual . , .


, return- mapStateToProps , . , , - . UNITS - selectUserUnits(state, userId). .


reselect


.. state — , : state.todos[42].title. , . , . , redux .


reselect — , . -, readme , . -, reselect . -, ( , ) .


2 reselect , .

. , , , mapStateToProps.


reselect . , :


export const selectPriceWithDiscountByProductId = (state, id) => {
  const {price, discount} = state.product[id];

  return {price, discount};
};

export const selectTagsByProductId = (state, id) => state.product[id].tags || [];

, mapStateToProps, . , tags. , reselect ( faiwer — :) ).


, :


const EMPTY_ARRAY = Immutable([]);

export const selectTagsByProductId = (state, id) => state.product[id].tags || EMPTY_ARRAY;

3 reselect , .

. . const selectUserById = (state, id) => state.user[id] ,


reselect . , createSelector, .


createSelector(...inputSelectors | [inputSelectors], resultFunc)

inputSelectors — , . resultFunc, .


// selectors.js

const selectUserTagById = (state, userId) => state.user[userId].tag;
const selectPictures = state => state.picture;

const selectRelatedPictureIds = createSelector(
  selectUserTagById,
  selectPictures,
  (tag, pictures) => (
     Object.values(pictures)
       .filter(picture => picture.tags.includes(tag))
       .map(picture => picture.id)
  )
)

, , , . , .


, reselect , :


  • ( shallowEqual), . , id , reselect
  • inputSelectors ( shallowEqual), . , - , reselect selectUserTagById selectPictures. pictures tag, reselect .

4 .

selectUser({user}) inputSelectors


. reselect, : 1. , . , . , RelatedPictures,


// RelatedPicturesContainer.js

import {connect} from 'react-redux';
import {RelatedPictures} from '../components';
import {selectRelatedPictureIds} from '../selectors';

const mapStateToProps = (state, {userId}) => {
  return {
    pictureIds: selectRelatedPictureIds(state, userId)
  }
};

export default connect(mapStateToProps)(RelatedPictures);


const RelatedPicturesList = ({userIds}) => (
  <div>
    {Array.isArray(userIds) && (
      userIds.map(id => <RelatedPictureContainer userId={id} />
    )}
  </div>
)

RelatedPicturesList , RelatedPictureContainer mapStateToProps pictureIds, selectRelatedPictureIds userId . , , RelatedPictures ShouldComponentUpdate, .


reselect


5 .

, mapStateToProps , . react-redux , mapStateToProps, , mapStateToProps


// selectors.js
const selectUserTagById = (state, id) => state.user[id].tag;
const selectPictures =  (state, id) => state.picture;

const createRelatedPictureIdsSelector = () => createSelector(
  selectUserTagById,
  selectPictures,
  (tag, pictures) => (
     Object.values(pictures)
       .filter(picture => picture.tags.includes(tag))
       .map(picture => picture.id)
  )
)

// RelatedPicturesContainer.js

import {connect} from 'react-redux';
import {RelatedPictures} from '../components';
import {createRelatedPictureIdsSelector} from '../selectors';

const createMapStateToProps = () => {
  const selectRelatedPictureIds = createRelatedPictureIdsSelector();

  return (state, {userId}) => {
    return {
      pictureIds: selectRelatedPictureIds(state, userId)
    };
  };
};

export default connect(createMapStateToProps)(RelatedPictures);

RelatedPicturesContainer selectRelatedPictureIds. 1. - userId, . . , react-, relatedPictureIds , GC .


. "? ? , , ?". re-reselect, . , mapStateToProps


6 re-reselect

. , . , , , , , Node.js Server Side Rendering. , , , .


connect


mapStateToProps. , connect ' .


connect(mapStateToProps, mapDispatchToProps, mergeProps, options)

, react-redux . , mapStateToProps (state), . mapDispatchToProps.


7 mapStateToProps mapDispatchToProp connect'

, mergeProps . mergeProps ( ) mapStateToProps mapDispatchToProps. , , , . . , : connect(mapStateToProps, null, x => x).


react-redux . , mapStateToProps null, ( , ). , . mapStateToProps ( ), mergeProps .


, options connect. . , mapStateToProps, mapDispatchToProps mergeProps shallowEqual. . , mapStateToProps.


8 connect, . , shouldComponentUpdate — .


redux . -, . , .


React-redux — . , ( MVVM). , , . , , . shouldComponentUpdate (useRef ).


Eh bien, dans la très, très conclusion. J'espère que le lecteur trouvera au moins quelques conseils utiles - cela signifie que ce n'est pas en vain qu'il a écrit. Tout castor)


All Articles