2

My application is not able to redirect using:

dispatch(push("/welcome"));

I tried to follow the tutorial here but using a ConnectedRouter.

The redirect seems to work as the URL changes now, but only the URL location changes and the view does not re-render and doesn't display the html for the /welcome page.

https://7wm1z5q666.codesandbox.io/welcome)

I created a live running example of my scenario, hoping someone can help me make sure I have all the pieces in place.

https://codesandbox.io/s/7wm1z5q666

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

2

Your redirect code is fine.

Looks like you have problem here:

const mapStateToProps = state => ({
  email: state.users.email,
});

With an actual string, the page will correctly redirect and render.

const mapStateToProps = state => ({
  email: 'abcd@efg.com',
});

state.users is undefined, and it's because for some reason your state here is not pointing to the redux store, but react-router. I would look into your redux and router setup in Root.js.

Eric
  • 2,635
  • 6
  • 26
  • 66
1

Here is why view doesn't get updated when you change your route. And it is also described in react-redux troubleshooting section.

If your views depend on global state or React “context”, you might find that views decorated with connect() will fail to update.

This is because connect() implements shouldComponentUpdate by default, assuming that your component will produce the same results given the same props and state. This is a similar concept to React’s PureRenderMixin.

So the problem is within your ConnectedSwitch which will work if you change it to:

const ConnectedSwitch = connect(
  state => ({
    location: state.location
  }),
  null,
  null,
  { pure: false }
)(Switch);

or

const ConnectedSwitch = withRouter(
  connect(state => ({
    location: state.location
  }))(Switch)
);

It seems to me that state.location even though is coming from redux is being mutated not updated. That's why shouldComponentUpdate implemented by connect returns false.

Unfortunately, I don't get:

Cannot read property 'email' of undefined

so I don't know how to help you with that.

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
  • how can I figure out which component is being called but not re-rendered? In a more complicated reactjs app is there a way to debug this? Will my components shouldComponentUpdate be overriden? – Blankman Apr 02 '18 at 15:54
  • 1
    @Blankman You need to look for implementations of [shouldComponentUpdate](https://reactjs.org/docs/react-component.html#shouldcomponentupdate). If a component receives new props react will always re-render... unless shouldComponentUpdate returns false (by default always true). `connect` does shallow equal to received props and if they didn't change it will return false in this hook. This is why immutability is so important to always get a fresh view. – Tomasz Mularczyk Apr 02 '18 at 16:05