1
所以我想用主页上的登录表单做一个简单的应用程序,然后重定向到仪表板。在试图制作/仪表盘页面时,我遇到了一个问题。这里是代码:重定向在React路由器中不起作用
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {Redirect} from 'react-router-dom'
class DashBoard extends Component {
constructor(props) {
super(props);
}
render() {
if (this.props.auth.token) {
return (
<h2>Here will be dashboard with items.</h2>
);
} else {
return <Redirect to={{pathname: '/'}} push/>
}
}
}
export default connect(
(state) => {
return state;
}
)(DashBoard);
问题是url更改,但组件实际上并没有呈现自己。那么为什么仪表板中的重定向不起作用?
编辑:我终于设法从家庭组件做出重定向,但对仪表板仍然不起作用!
import React, {Component} from 'react';
import {connect} from 'react-redux';
import * as actions from 'actions';
import {Redirect} from 'react-router-dom';
class Home extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentWillReceiveProps(nextProps) {
console.log('nextProps');
if (!nextProps.isLoading) {
if (nextProps.auth.error) {
console.log('error');
} else if (nextProps.auth.token) {
console.log('success');
} else {
console.log('something else');
}
}
}
handleSubmit(e) {
let {isLoading, auth, dispatch} = this.props
e.preventDefault();
let email = this.refs.email.value;
let password = this.refs.password.value;
dispatch(actions.login(email, password))
}
render() {
let {isLoading, auth} = this.props;
let renderLoading =() => {
if (isLoading) {
return 'Loading...'
} else {
return 'Submit';
}
}
let renderMessage =() => {
if (auth.error) {
return <p className="error-message">{auth.error}</p>;
} else if (auth.token) {
return <p className="success-message">You have successfully logined in.</p>
} else {
return <p></p>
}
}
if (auth.token) {
return (<Redirect to='/dashboard'/>)
}
return (
<div className="form-container">
{renderMessage()}
<form onSubmit={this.handleSubmit}>
<div className="field">
<label>First Name</label>
<input type="text" name="email" placeholder="First Name" ref="email" />
</div>
<div className="field">
<label>Password</label>
<input type="text" name="password" placeholder="Last Name" ref="password"/>
</div>
<button className="form-button" type="submit">{renderLoading()}</button>
</form>
</div>
);
}
}
export default connect(
(state) => {
return state;
}
)(Home);
这不适合我。我刚刚发现重定向后,如果我查看react开发工具并打开路由器上下文,那么我会看到该位置是/仪表板,但在浏览器中显示为localhost:3001。可能是这个问题?但为什么然后实际上Home组件中的相同代码有效? –
您是否尝试在react-redux的connect函数中使用'pure:false'?你可以尝试这种方式:'connect(null,null,null,{pure:false})(Component)'。 [API](https://github.com/reactjs/react-redux/blob/master/docs/api.md)澄清了此选项的效果。 –
@AndreyLuiz,不幸的是,没有工作。任何建议,为什么重定向家庭组件的作品和仪表板它不? –