Processing view logic in reduction

I find that mine is mapStateToPropsincreasing in complexity.

For example, for several connected components, I did something like this:

const mapStateToProps = (state) => {
  return {
    activeAsset: state.assets.byId[state.assets.activeAssetId].attributes
  }
}

Problem No. 1: It is quite obvious that the above code could be protected with some conventions, as it is activeAssetIdnot always specified, which will lead to the fact that the above would cause an error.

Problem No. 2: Suppose I want to get the current activeAssetin several components, which I now need to duplicate above.

I heard about reselect , but I'm not quite sure if this is the right choice here, as it seems to be used specifically with memoized functions.

Please excuse me if the answer is obvious enough, I'm pretty new to the reduct ecosystem.

+4
source share
1 answer

A safe solution is to use a selector. Selectors are reusable functions that know the state shape in the store and can create derived data.

In your case, it could be your selector:

const getAssetAttributes = ({ assets }) =>  (assets.byId[state.assets.activeAssetId] && assets.byId[state.assets.activeAssetId].attributes) || null; // if the asset exists and has attributes return it, if not return null

Using:

const mapStateToProps = (state) => {
  return {
    activeAsset: getAssetAttributes(state)
  }
}

selectors. Reselect , . , , .

+4

Source: https://habr.com/ru/post/1661594/


All Articles