状态未映射到道具react-redux

时间:2017-06-06 14:57:53

标签: javascript reactjs redux

我有一个简单的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);

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

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

减速机:

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

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

  

this.props.loginObj.loginState - this.props为null

更新: LoginForm的:

2 个答案:

答案 0 :(得分:0)

  import {bindActionCreators} from 'redux'; //must include


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

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

答案 1 :(得分:0)

首先,您更正了mapStateToProps方法。它没有回报价值。它从方法的语法中清楚地显示出来。

第二个为什么你使用this.props.loginObj.loginState?这个抽象级别是错误的。正如您提到loginObj作为道具,那么为什么要在那里抽象loginState属性?它不起作用。

在redux中,您应该将props限制为州内的同一个对象。例如,如果你想要来自州的待办事项,那么请将待办事项称为道具。如果你想要一些todos的属性,那么把它传递给道具(这个代码)或通过儿童道具。

我不了解您的商店,但该组件应如下所示:

    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);
相关问题