我的组件中的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 {}
答案 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