reduxjs / react-redux

Official React bindings for Redux
https://react-redux.js.org
MIT License
23.37k stars 3.37k forks source link

mapStateToProps being run for non-instantiated components #195

Closed 0rvar closed 8 years ago

0rvar commented 8 years ago

Minimal test case: https://jsfiddle.net/69z2wepo/21767/

The mapStateToProps function supplied to ReactRedux.connect is run too often, even when the connected component is not created / added to the react tree. When it is mounted, it is run too often; I count 3 times for a single store update; before it's created (?!), before it's rendered, after it's rendered (why?)

This is problematic, as I access a fields of state objects that may be nulled out. Ideally, the maybeRender would work correctly, and I would not have to guard against nulls in my mapStateToProps, but right now I'd have to do something like

if(!renderPredicate(state)) {
  return;
}

at the top of my mapStateToProps.

The intended solution of hiding a component through functional composition appeals to me. It allows me to use some lifecycle logic in the connected component.

0rvar commented 8 years ago

I found the problem. I was lexically shadowing Component in the maybeRender function, so I extended the component I was trying to conditionally render. Working fiddle (only changed maybeRender): https://jsfiddle.net/re6tmuw9/5/

Closing this now, sorry if I caused anybody to spend time on this one.