2016-09-26 77 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]}