我正在将redux添加到现有应用中,但我无法更新订阅该商店的组件的状态。我设置的最小块:
DivsContainer.js
const DivsContainer = React.createClass({
propTypes: {
collections : PropTypes.array.isRequired
},
render() {
return (
<div onClick={this.props.onClick}>
{this.props.collections.map((coll, i) => (
<div
key={coll.id}
name={coll.name}
/>
))}
</div>
)
}
})
function mapStateToProps(state, ownProps) {
return {
collections: state.collectionsReducer.collections,
}
}
function mapDispatchToProps (dispatch, ownProps) {
return {
onClick: () => {
dispatch(addCollection())
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DivsContainer)
Reducers.js
import {combineReducers} from 'redux'
import {ADD_COLLECTION, REMOVE_COLLECTION} from './actions'
const initialState = {
collections: [
{
id: 1,
name: "mock",
}
}
]
}
function collectionsReducer(state = initialState, action) {
switch (action.type) {
case ADD_COLLECTION:
return [
...state,
{
id: action.id,
name: action.name,
}
]
default:
return initialState
}
}
const rootReducer = combineReducers({collectionsReducer})
export default rootReducer
actions.js
export const ADD_COLLECTION = 'ADD_COLLECTION'
let nextCollectionId = 2
export function addCollection() {
return {
type: ADD_COLLECTION,
id: nextCollectionId++,
name: 'mock',
}
}
调用reducer,所以我怀疑在返回新状态对象时出现问题(reducers不正确),因为我得到:
未捕获的TypeError:无法读取未定义渲染的属性“map” @ DivsContainer.js:
答案 0 :(得分:2)
你的减速机有点搞砸了。 collectionsReducer
返回一个数组,但您的initialState
是一个包含数组的对象。
reducer可能应该是:
return {
...state,
collections: [...state.collections, {id: action.id, name: action.name}],
};
并且您的mapStateToProps
应为:
function mapStateToProps(state, ownProps) {
return {
collections: state.collections,
};
}
因为您将state
映射到props
,而您的州的形状为{collections: []}
而不是{collectionsReducer: collections: []}
答案 1 :(得分:0)
这是因为在你的reducer中,ADD_COLLECTION返回一个数组[something],它不是{collections:something}。所以减速器不再有收藏品了,它抱怨&#39; map&#39;未定义的。您需要在ADD_COLLECTION
中返回{collections:[something]}