问题
I'm new to redux and want to learn it, I want to make redirect to dashboard content after succesful login, here is my code:
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)
reducer:
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
why it doesn't want to change state of dashboard and render proper content? Thanks
EDIT here I add code where i dispatch my reducer: Login:
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);
when I try to console log logged in mapStateToProps then i can see that logged has changed to true, but unfortunatelly no visible effect on the dashboard. My idea is that maybe it doesn't rerender after changing state but I dont know...
回答1:
Change
{this.state.logged ?
<div>
<p>Hello</p>
</div>
: Login()
</div>
)}
with
{this.props.logged ?
<div>
<p>Hello</p>
</div>
: Login()
</div>
)}
回答2:
mapStateToProps maps "state" (redux state) to "props" (component props). Not "state" to "state"
class Dashboard extends Component {
render() {
const { classes, logged } = this.props
return (
<div>
{logged ? (
<div>
<p>Hello</p>
</div>
) : (
Login()
)}
</div>
)
}
}
Also do not specify second argument in mapStateToProps if you don't actually use it. This prevents optimization done by react-redux.
const mapStateToProps = (state) => {
return {
logged: state.logged
}
}
来源:https://stackoverflow.com/questions/56899702/mapstatetoprops-doesnt-change-state