状态未映射到props react-redux

IT技术 javascript reactjs redux
2021-05-24 15:32:37

我有一个简单的 LoginForm,我尝试从 redux 映射状态以进行react。这是我来自 LoginForm.js 的代码:

 export class LoginForm extends React.Component {
    render() {

            console.log("**** FORM print store");
            console.log(store.getState());
            console.log("**** FORM print props");
            console.log(this.props);

            if(this.props.loginObj.loginState=='true') { // error here
                console.log('yes');
            }

            return (
            <div><div/>);
            );
          }
      }

const mapStateToProps = (state) => ({
    loginObj : state.loginObj
});

const mapDispatchToProps = (dispatch) => ({
  doLogin,
  changeText,
});

export default connect(  
  mapStateToProps,
  mapDispatchToProps,
)(LoginForm);

减速器包含属性 loginObj,如果我打印我看到的商店:

loginObj:   
    Object { loginState="false",  user="",  password=""}

减速器:

const reducers = combineReducers({
    loginObj: loginReducer
});
...

但是,当我尝试访问props时,似乎 this.props 是空的。

this.props.loginObj.loginState - this.props 为空

更新:登录表单:

2个回答
  import {bindActionCreators} from 'redux'; //must include


  function mapStateToProps(state){
         return {    
           loginObj : state.loginObj
          }
        }

   function mapDispatchToProps(dispatch){
       return bindActionCreators({doLogin,changeText},dispatch)
    };

首先你正确你的mapStateToProps方法。它没有返回值。它从方法的语法中清楚地显示出来。

第二,你为什么使用this.props.loginObj.loginState这个抽象层次是错误的。正如您所提到的loginObjprops,那么为什么要loginState在那里抽象属性?它不会工作。

在 redux 中,您应该将 props 限制为状态中的同一对象。例如,如果您想要来自 state 的 todos,那么将 todos 作为 props 提及。如果你想要一些 todos 的属性,那么将它传递给 props(对于这个代码)或通过 children props。

我不知道你的商店,但组件应该是这样的:

    export class LoginForm extends React.Component {
    render() {

    console.log("**** FORM print store");
    console.log(store.getState());
    console.log("**** FORM print props");
    console.log(this.props);

    if (this.props.loginObj.loginState == 'true') { // error here
      console.log('yes'); 
    }
      // for this issue you could view at this point - 
      // store.getState().loginObj.propertyyouwant only if you have 
      // imported main store in this current file
    return (
      <div>
      </div>
            );
          }
      }

    const mapStateToProps = (state) => {
      return { loginObj: state.loginObj}    
    };

    const mapDispatchToProps = (dispatch) =>
    {
     return {
      doLogin,
      changeText,}
    };


    export default connect(  
     mapStateToProps,
     mapDispatchToProps,
    )(LoginForm);