我正在尝试制作一个简单的应用程序,主页上有登录表单,然后重定向到仪表板。当我尝试使/dashboard页面私有化时,遇到了问题。以下是代码:
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);
pure: false
吗?你可以这样尝试:connect(null, null, null, {pure: false})(Component)
。如果为true,API会解释此选项的作用。 - Andrey Luiz