2017-01-22 143 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

在这部分代码中,我可以粘贴它吗?因为如果我粘贴渲染。我得到错误 –