2016-10-28 57 views
0

我試圖在反應組件上顯示一個存儲值。但是,這返回未定義。我的行動和減速機工作正常,並更新狀態。全局狀態值沒有顯示在減號中

但是組件應該在每次狀態改變時重新呈現。看起來像mapStateToProps或連接功能無法正常工作。

這裏是我的代碼:

import React, {Component} from 'react'; 
import ReactDOM from 'react-dom'; 
import {Provider, connect} from 'react-redux'; 
import {createStore} from 'redux'; 

class Sam extends Component{ 
    constructor(props){ 
    super(props) 
    } 

    render(){ 
    return(
     <div> 
     {this.props.globalState.no} // Uncaught TypeError: Cannot read property 'no' of undefined 
     <button onClick={()=>{store.dispatch(incAction)}}>Click Me</button> 
     </div> 
    ) 
    } 
} 


const reducer = (state={name:'Piyush',no:0}, action) => { 

    if(action.type==='INC'){ 
    console.log("INC"); 
    console.log("getstate => ", store.getState()); 
    console.log("Old state => ", state); 
    console.log("New State => ", Object.assign({}, state, {no:state.no + 1})); 
    return Object.assign({}, state, {no:state.no + 1}) 
    } 
    return state; 
} 

const incAction = { 
    type:'INC' 
} 

const mapStateToProps = (globalState) => { 
    return {globalState:globalState.reducer} 
} 

const store = createStore(reducer); 
ReactDOM.render(<Provider store={store}><Sam /></Provider>, document.getElementById('app')) 
export default connect(mapStateToProps)(Sam) 
+0

@ChristopherChiche –

回答

1

看起來你mapStateToProps不正確。它應該是這樣的:

const mapStateToProps = (globalState) => { 
    return {globalState}; 
} 

由於當前的mapStateToProps只是返回{globalState: globalState.reducer},那麼當您嘗試訪問this.props.globalState.no它不存在,因爲globalState.reducer不存在。您的globalState看起來像{name:'Piyush',no:0}

+0

我這樣做了,但沒有奏效。看起來像mapStateToProps沒有被調用,因爲裏面的任何控制檯信息也沒有顯示在控制檯中。 –

+0

要使mapStateToProps工作,我做了以下工作: var Cont = connect(mapStateToProps)(Sam); ReactDOM.render(,document.getElementById('app')); 導出默認Cont; 現在組件也呈現,但顯示未定義的商店值。 –