cki*_*m16 5 redirect reactjs redux react-router-dom
自从我开始使用react/redux以来我第一次使用react-router-dom应用程序而且我在使用Redirect组件时遇到了麻烦.
我想Redirect在身份验证成功时触发,但在身份验证后它不会重定向到我想要的页面.
index.js
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import App from './components/app';
import Page1 from './containers/page1';
import Signin from './containers/auth/signin';
import Reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);
const store = createStoreWithMiddleware(Reducers);
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<Route path="/" component={App}/>
<Route path="/" component={Signin}/>
<Route path="/signin" component={Signin}/>
<Route path="/page1" component={Page1}/>
</div>
</Router>
</Provider>
, document.querySelector('.container'));
Run Code Online (Sandbox Code Playgroud)
signin.js
import { BrowserRouter as Route, Redirect } from 'react-router-dom';
import { userSignin } from '../../actions/index';
class Signin extends Component {
constructor(props) {
super(props);
this.state = { username: '', password: '' };
this.handleSubmit = this.handleSubmit.bind(this);
this.handleUsernameChange = this.handleUsernameChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
componentWillUpdate(nextProps) {
if (this.props.authenticated !== nextProps.authenticated) {
if (nextProps.authenticated) {
console.log('true?', nextProps.authenticated)
return (
<Redirect to="/page1" />
);
}
}
}
handleSubmit(e) {
e.preventDefault();
this.props.userSignin({ username: this.state.username, password: this.state.password });
this.setState({ username: '', password: '' });
}
.....
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
placeholder="username"
value={this.state.username}
onChange={this.handleUsernameChange}
/>
<input
placeholder="password"
type="password"
value={this.state.password}
onChange={this.handlePasswordChange}
/>
<span>
<button type="submit">SIGNIN</button>
</span>
{this.renderError()}
</form>
);
}
}
function mapStateToProps(state) {
return {
authenticated: state.auth.authenticated,
errMsg: state.auth.err
};
}
function mapDispatchToProps(dispatch) {
return {
userSignin: ({ username, password }) => dispatch(userSignin({ username, password }))
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Signin);
Run Code Online (Sandbox Code Playgroud)
在此代码中,这会记录true?但不会重定向到/page1.
正如我所提到的,这是我第一次使用react-router-dom库,并为我在代码中遇到的任何愚蠢错误道歉.
谢谢你,请有识别我!
而不是Redirect使用this.props.history.push('/path1')和包装connect()in withRouter(从react-router导入),如下所示:
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Signin));
Run Code Online (Sandbox Code Playgroud)
如果要使用Redirect,请在本地状态下维护经过身份验证的值,将其更新componentWillReceiveProps并有条件地呈现<Redirect />in render方法.
| 归档时间: |
|
| 查看次数: |
5464 次 |
| 最近记录: |