2016-09-26 50 views
1

我正在将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:

回答

2

你的减速机有点搞砸了。 collectionsReducer返回一个数组,但是您的initialState是一个带有数组的对象。

的减速或许应该是:

return { 
    ...state, 
    collections: [...state.collections, {id: action.id, name: action.name}], 
}; 

和你mapStateToProps应该是:

function mapStateToProps(state, ownProps) { 
    return { 
     collections: state.collections, 
    }; 
} 

因为你映射stateprops和你的国家有{collections: []}{collectionsReducer: collections: []}

形状
0

这是因为在你的reducer中,ADD_COLLECTION返回一个a rray [某事],它不是{collections:something}。所以reducer不再有集合,它抱怨未定义的'map'。您需要在您的ADD_COLLECTION中返回{collections:[something]}