2017-01-22 139 views
1

我正在使用React Redux構建應用程序。狀態未定義(reactJS)

這是我的減速器:

import { INCOME_LIST } from '../actionTypes' 

import Immutable from 'immutable' 

const initialUserState = { 
    list: [{ 
        id: 1, 
        label: 'List item 1' 
       }, 
       { 
        id: 2, 
        label: 'List item 2' 
       }] 
} 

const listReducer = function(state = [initialUserState], action) { 
    switch(action.type) { 
    case 'INCOME_LIST': 
     return Object.assign({}, state, { list: action.data }); 

    default: return state; 
    } 

} 

export default listReducer 

這是我的組件:

import React, { Component, PropTypes } from 'react' 
import { Link, browserHistory } from 'react-router' 
import { connect } from 'react-redux' 
import axios from 'axios' 

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

render() { 
console.log(this.props.items) 
     return (
      <div> 
       test 
      </div> 
     ) 
    } 

} 

const mapStateToProps = function(store) { 
    return { 
    items: state.list 
    }; 
} 

export default connect(mapStateToProps)(Income); 

控制檯說: '未定義' 爲什麼執行console.log(this.props.items)獲得undifined? 如何正確的方式從減速機獲得狀態?可能在那裏犯錯?

回答

1

三樣東西,我可以看到,

首先在mapStateToProps功能您所定義的變量作爲存儲和使用它作爲狀態。將其更改爲這個

const mapStateToProps = function(state) { 
    return { 
    items: state.list 
    }; 
} 

而且構造後,你有一個額外的}那你當你把你console.log()render()功能的錯誤的原因。

同樣在你的reducer中,你定義初始狀態的方式使它成爲一個數組。你應該糾正,像state='initialUserState

完整代碼

減速

import { INCOME_LIST } from '../actionTypes' 

import Immutable from 'immutable' 

const initialUserState = { 
    list: [{ 
        id: 1, 
        label: 'List item 1' 
       }, 
       { 
        id: 2, 
        label: 'List item 2' 
       }] 
} 

const listReducer = function(state = initialUserState, action) { 
    switch(action.type) { 
    case 'INCOME_LIST': 
     return Object.assign({}, state, { list: action.data }); 

    default: return state; 
    } 

} 

export default listReducer; 

組件

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


render() { 
console.log(this.props.items) 
     return (
      <div> 
       test 
      </div> 
     ) 
    } 

} 

const mapStateToProps = function(state) { 
    return { 
    items: state.list 
    }; 
} 

export default connect(mapStateToProps)(Income); 
+0

這樣做,但在控制檯中我得到未定義.....爲什麼我無法獲得狀態形式我的reducer? –

+0

嘗試和console.log(state.list)裏面在mapStateToProps功能,看看它是否會記錄什麼 –

+0

進行屏幕https://i.imgsafe.org/4e36750cf3.png –

1

您的論點被命名爲store,但您將其稱爲state。 嘗試:

const mapStateToProps = function(state) { 
    return { 
    items: state.list 
    }; 
} 
+0

是的,你的權利。我可以在哪裏製作сonsole.log(物品);考試。在哪個部分代碼?因爲我嘗試在渲染功能中執行並出現錯誤。對不起,我是新的反應 –

+0

無論'mapStateToProps'的返回都映射到組件的道具。嘗試'console.log(this.props.items)'。 –

+0

在這部分代碼中,我可以粘貼它嗎?因爲如果我粘貼渲染。我得到錯誤 –