2017-02-12 85 views
0

在我的組件中有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) 

我需要從國家

組件

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

組件。你是否試圖訪問'this.props.status'?您應該展示完整的組件,以便人們可以理解您的問題。 –

+0

是啊 我想從'this.props.status'獲取數據並獲取'undefined'我不知道爲什麼它會出現這樣的 –

+1

可能有很多原因,很難說?你有沒有將reducer包含在'combineReducers'函數中?你是否符合你的減速器中的任何情況? –

回答

1

得到status您不能訪問是constructor內異步道具。由於constructor只會在您實例化組件時執行一次。當您實例化組件時,異步調用尚未響應,因此this.props.status未定義。

你可以使用從componentWillReceiveProps陣營生命週期方法例如:

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

此方法將被執行每次一個道具連接,或通過,該組件將發生變化。 你也可以在render裏面使用this.props.status,因爲每次改變一個道具都會執行這個。

爲了更好地理解的反應週期,你可以有看不同的方法可用,在這裏:一旦你通過國家與`mapStateToProps`組件的道具,它應該是通過道具訪問https://facebook.github.io/react/docs/react-component.html

相關問題