mapStateToProps不会更改状态

时间:2019-07-05 08:50:14

标签: reactjs redux

我是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

为什么不想更改仪表板状态并呈现适当的内容?谢谢

在这里编辑,我在派遣我的reducer的地方添加代码: 登录名:

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,但是不幸的是,在仪表板上没有可见的影响。我的想法是,更改状态后可能不会重新渲染,但我不知道...

2 个答案:

答案 0 :(得分:2)

WORKDIR /app COPY Test.txt . 将“状态”(redux状态)映射到“ props”(组件props)。不是从“状态”到“状态”

mapStateToProps

如果您实际上没有使用第二个参数,也不要在class Dashboard extends Component { render() { const { classes, logged } = this.props return ( <div> {logged ? ( <div> <p>Hello</p> </div> ) : ( Login() )} </div> ) } } 中指定第二个参数。这样可以防止mapStateToProps完成优化。

react-redux

答案 1 :(得分:0)

更改

{this.state.logged ?
<div>
<p>Hello</p>
</div>
: Login()
</div>
)}

{this.props.logged ?
<div>
<p>Hello</p>
</div>
: Login()
</div>
)}