我是 redux 的新手并想学习它,我想在成功登录后重定向到仪表板内容,这是我的代码:
class Dashboard extends Component {
state = {
logged: false
};
render() {
const { classes } = this.props;
console.log(this.state.logged)
return (
<div>
{this.state.logged ?
<div>
<p>Hello</p>
</div>
: Login()
</div>
)}
}
const mapStateToProps = (state, props) => {
return {
logged: state.logged
}
}
export default connect(mapStateToProps)(Dashboard)
减速器:
const initialState = {
login: [],
logged: false
}
function rootReducer(state = initialState, action) {
switch(action.type) {
case VALIDATE_LOGIN:
return {
// logged: action.text.name == "a" && action.text.password == "b" ? true : false,
...state,
logged: true
}
default:
return state
}
}
export default rootReducer
为什么它不想更改仪表板的状态并呈现正确的内容?谢谢
在这里编辑我添加代码,在那里我调度我的减速器:登录:
class Login extends Component {
state = {
name: "",
password: ""
};
handleLogin = () => {
this.props.LogIn(this.state)
}
render() {
return (
<div>
<Typography variant="h3">
Login Form
</Typography>
<form>
<TextField label="name" onChange={el => this.setState({name: el.target.value})} />
<TextField label="password" type="password" onChange={el => this.setState({password: el.target.value})} />
<Button onClick={this.handleLogin}>Login</Button>
</form>
</div>
);
}
}
const dispatchToProps = dispatch => {
return {
LogIn: login => dispatch(LogIn(login))
}
}
export default connect(null, dispatchToProps)(Login);
当我尝试控制台登录 mapStateToProps 时,我可以看到记录已更改为 true,但不幸的是在仪表板上没有可见效果。我的想法是,也许它在更改状态后不会重新渲染,但我不知道......