组件中的空状态(反应还原)

时间:2017-02-12 18:53:34

标签: javascript reactjs redux

我的组件中的state出现问题。 我试图从我的reducer中获取状态,但state只是空undefined

这是我的actionCreator

export function checkLogin() {
return function(dispatch){
    return sessionApi.authCheck().then(response => {
        dispatch(authSuccess(true)); 
    }).catch(error => {
        throw(error)
    })
 }
}

我的减速机

export const authStatus = (state = {}, action) => {
switch(action.type){
    case AUTH_FALSE:
            return{
                status: action.status
            }
    case AUTH_TRUE:
            return {
                ...state,
                status: action.status
            };
    default:
        return state;
  }
};

这是我的组件,我试图获得状态

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

const mapDispatchToProps = (dispatch:any) => {
  const changeLanguage = (lang:string) => dispatch(setLocale(lang));
  const checkAuth = () => dispatch(checkLogin());
  return { changeLanguage, checkAuth }
};

@connect(mapStateToProps, mapDispatchToProps)

我需要从州获得status

组件

import * as React from "react";
import  Navigation  from './components/navigation';
import { connect } from 'react-redux';
import { setLocale } from 'react-redux-i18n';
import cookie from 'react-cookie';
import {checkLogin} from "./redux/actions/sessionActions";

class App extends React.Component<any, any> {
  constructor(props:any) {
    super(props);
    this.state = {
      path: this.props.location.pathname
    };
  }
  componentDidMount(){
    this.props.checkAuth();
    this.props.changeLanguage(cookie.load('lang'));
  }
  componentWillUpdate(){
  }

  render() {
    return (
      <div>
        <Navigation path={this.state.path} />
          {this.props.children}
      </div>
    )
  }

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

const mapDispatchToProps = (dispatch:any) => {
  const changeLanguage = (lang:string) => dispatch(setLocale(lang));
  const checkAuth = () => dispatch(checkLogin());
  return { changeLanguage, checkAuth }
};

@connect(mapStateToProps, mapDispatchToProps)
export class Myapp
extends App {}

1 个答案:

答案 0 :(得分:1)

您无法访问constructor内部异步的道具。因为constructor只会在实例化组件时执行一次。当您实例化组件时,异步调用尚未响应,因此this.props.status未定义。

您可以使用React生命周期方法中的componentWillReceiveProps,例如:

componentWillReceiveProps(nextProps) {
  console.log(nextProps.status);
}

每次连接或传递给组件的prop都会发生变化时,将执行此方法。 您也可以在this.props.status内使用render,因为每次改变道具时都会执行此{。}}。

为了更好地理解反应生命周期,您可以查看可用的不同方法:https://facebook.github.io/react/docs/react-component.html