我正在使用React Redux构建应用程序。
这是我的减速机:
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);
控制台说:'undefined' 为什么console.log(this.props.items)得到了解开? 如何正确地从减速机获得状态?可能是错误吗?
答案 0 :(得分:1)
您的参数名为store
,但您将其称为state
。
尝试:
const mapStateToProps = function(state) {
return {
items: state.list
};
}
答案 1 :(得分:1)
我能看到的三件事,
首先在mapStateToProps
函数中,您将变量定义为store并将其用作状态。将其更改为此
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);