简体   繁体   中英

React-router-redux setState warning after redirect

I'm building an admin app for a project with react, redux, react-router and react-router-redux . React-router is v4.0.0 , react-router-redux is v5.0.0-alpha.3 (installed with npm install react-router-redux@next ). What I'm trying is:

  1. Load app,
  2. Perform an async call to backend to see if the user is logged in (token stored in a cookie),
  3. If user is not logged in, redirect to /login and render Login component.

For async actions I'm using redux-thunk .

Root.js

import React, { Component, PropTypes } from 'react';
import { Provider, connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import { ConnectedRouter, push } from 'react-router-redux';

import Login from './Login';

const App = () => <h1>Dashboard</h1>;
const NotFound = () => <h1>Not found :(</h1>;

class Root extends Component {

  // use componentDidMount as recommended here:
  // https://facebook.github.io/react/docs/react-component.html#componentdidmount
  componentDidMount() {
    const { dispatch, user } = this.props;
    if (!user) {
      dispatch(push('/login'));
    }
  }

  render() {
    const { store, history } = this.props;
    return (
      <Provider store={store}>
        <ConnectedRouter history={history}>
          <div>
            <Switch>
              <Route exact path='/' component={App} />
              <Route exact path='/login' component={Login} />
              <Route component={NotFound} />
            </Switch>
          </div>
        </ConnectedRouter>
      </Provider>
    );
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired,
  user: PropTypes.shape({
    email: PropTypes.string.isRequired
  })
};

const mapStateToProps = state => ({
  ready: state.ready,
  user: state.user
});

export default connect(mapStateToProps)(Root);

Login.js

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

import {
  loginFormChange,
  loginFormSubmit
} from '../actions';

class Login extends Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const { target } = event,
      { value, name } =  target,
      { dispatch } = this.props;
    dispatch(loginFormChange({
      [name]: value
    }));
  }

  handleSubmit(event) {
    event.preventDefault();
    const { dispatch, login } = this.props,
      { email, password } =  login;
    dispatch(loginFormSubmit({
      email,
      password
    }));
  }

  render() {
    const { login } = this.props,
      { email, password } = login;
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="email" name="email" value={email} onChange={this.handleChange} />
        <input type="password" name="password" value={password} onChange={this.handleChange} />
        <button type="submit">Sign in</button>
      </form>
    );
  }
}

Login.propTypes = {
  dispatch: PropTypes.func.isRequired,
  login: PropTypes.shape({
    email: PropTypes.string.isRequired,
    password: PropTypes.string.isRequired
  }).isRequired
};

const mapStateToProps = state => ({
  login: state.login
});

export default connect(mapStateToProps)(Login);

actions.js

export const LOGIN_FORM_CHANGE = 'Login form change';
export const LOGIN_FORM_SUBMIT = 'Login form submit';
export const AUTHENTICATE_USER = 'Authenticate user';

export const loginFormChange = data => {
  const { email, password } = data;
  return {
    type: LOGIN_FORM_CHANGE,
    email,
    password
  };
};

export const loginFormSubmit = data => dispatch => {
  const { email, password } = data;
  return fetch('/api/auth/token', {
    headers: {
      'Authorization': 'Basic ' + btoa([ email, password ].join(':'))
    },
    credentials: 'same-origin'
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText);
      }
      return response.json();
    })
    .then(user => {
      // this line will throw setState warning:
      // Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
      dispatch(authenticateUser(user));
    });
};

export const authenticateUser = data => {
  const { email } = data;
  return {
    type: AUTHENTICATE_USER,
    email
  };
};

I want to point out that I'm using the recommended approach to async actions, described in redux documentation . I won't post my reducers for brevity. Finally:

index.js

import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import createHistory from 'history/createBrowserHistory';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';

import reducers from './reducers';
import Root from './containers/Root';

const history = createHistory(),
  middleware = [
    routerMiddleware(history),
    thunk
  ];

if (process.env.NODE_ENV !== 'production') {
  middleware.push(createLogger());
}

const store = createStore(
  reducers,
  applyMiddleware(...middleware)
);

render(
  <Root store={store} history={history} />,
  document.getElementsById('root')
);

So the warning gets thrown in the loginFormSubmit async action, when it tries to dispatch a sync authenticateUser action. Moreover it happens only after a redirect. I've tried different redirect approaches:

  • push from react-router-redux
  • Redirect component from react-router

I've also tried putting the redirect call in different places ( componentWillMount , componentDidMount , componentWillReceiveProps , conditional rendering inside of the component, using conditional PrivateRoute components as described in the react-router documentation , etc.), but nothing seems to work.

If there is no redirect in the first place (eg a user opens /login page instead of a protected one), than there is no warning.

Any help on the issue is very much appreciated.

I am having the same issue and basically it's a bug with the ConnectedRouter from react-router-redux v5.0.0-alpha.2 and alpha.3

It was actively being discussed for the past few days but now it's fixed in alpha 4 and the issue is closed:

https://github.com/ReactTraining/react-router/issues/4713

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM