我正在將REDX添加到現有的應用程序,並且更新訂閱商店的組件的狀態時遇到問題。最小信息塊用我的設置:在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',
}
}
減速器被調用,所以我懷疑問題發生在返回新的狀態對象時(減速器不正確),因爲我得到:
Uncaught TypeError: Cannot read property 'map' of undefined render @DivsContainer.js: