簡體   English   中英

組件中的空狀態(對redux的反應)

[英]Empty state in component ( react redux )

我的組件中的state有問題。 我正在嘗試從我的減速器獲取狀態,但是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 {}

您無法訪問在constructor內部異步的道具。 實例化組件時, constructor將只執行一次。 實例化組件時,異步調用尚未響應,因此this.props.status是未定義的。

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

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

每當連接或傳遞給組件的道具更改時,將執行此方法。 您還可以在render this.props.status內部使用this.props.status ,因為每次更改道具時也會執行一次。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM