gpt4 book ai didi

javascript - 重定向后的 React-router-redux setState 警告

转载 作者:行者123 更新时间:2023-11-30 08:27:37 24 4
gpt4 key购买 nike

我正在使用 React、redux、react-router 为项目构建管理应用程序和 react-router-redux . React-router 是 v4.0.0,react-router-redux 是 v5.0.0-alpha.3(使用 npm install react-router-redux@next 安装)。我正在尝试的是:

  1. 加载应用,
  2. 对后端执行异步调用以查看用户是否已登录( token 存储在 cookie 中),
  3. 如果用户未登录,则重定向到 /login 并呈现 Login 组件。

对于异步操作,我使用 redux-thunk .

根.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);

登录.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);

Action .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
};
};

我想指出,我正在使用推荐的异步操作方法,描述 in redux documentation .为简洁起见,我不会发布我的 reducer 。最后:

索引.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')
);

因此,当 loginFormSubmit 异步操作尝试分派(dispatch) sync authenticateUser 操作时,会引发警告。此外,它仅在重定向后发生。我尝试了不同的重定向方法:

  • 从 react-router-redux 推送
  • Redirect 来自 react-router 的组件

我还尝试将重定向调用放在不同的地方(componentWillMountcomponentDidMountcomponentWillReceiveProps、组件内部的条件渲染、使用条件 PrivateRoute 组件,如 react-router documentation 等中所述),但似乎没有任何效果。

如果一开始就没有重定向(例如,用户打开 /login 页面而不是 protected 页面),则不会有警告。

非常感谢有关此问题的任何帮助。

最佳答案

我遇到了同样的问题,基本上这是来自 react-router-redux v5.0.0-alpha.2 和 alpha.3 的 ConnectedRouter 的错误

过去几天一直在积极讨论,但现在它已在 alpha 4 中修复并且问题已关闭:

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

关于javascript - 重定向后的 React-router-redux setState 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com