[英]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.