代码之家  ›  专栏  ›  技术社区  ›  Boris Grunwald

使用组合生成器时无法将状态映射到道具

  •  0
  • Boris Grunwald  · 技术社区  · 6 年前

    const rootReducer = combineReducers({
        ctr:counter,
        res:result
    });
    
    const store = createStore(
        rootReducer,
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    );
    
    ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));
    registerServiceWorker();
    

    但是当我尝试将我的状态映射到给定组件的支柱时,状态是未定义的

    const mapStateToProps = state => {
        return {
            ctr: state.ctr.counter,
            storedResults: state.res.results //storedResults is undefined when I try to access it.
        }
    };
    

    计数器.js

    import * as actionTypes from "../actions";
    
    
    const initialState = {
        counter:0
    };
    
    const reducer = (state = initialState, action) => {
    
        switch (action.type) {
            case actionTypes.INCREMENT:
                return {
                    ...state,
                    counter: state.counter + 1
                };
            case actionTypes.DECREMENT:
                return {
                    ...state,
                    counter: state.counter - 1
                };
            case actionTypes.ADD:
                return {
                    ...state,
                    counter: state.counter + action.val
                };
            case actionTypes.SUBTRACT5:
                return {
                    ...state,
                    counter: state.counter - 5
                };
        }
    
        return state;
    };
    
    
    export default reducer;  
    

    import * as actionTypes from "../actions";
    
    
    const initialState = {
        result:[]
    };
    
    const reducer = (state = initialState, action) => {
    
        switch (action.type) {
            case actionTypes.STORE_RESULT:
                return {
                    ...state,
                    results:state.results.concat({id: new Date(), value:state.counter})
                };
            case actionTypes.DELETE_RESULT:
                // const id = 2;
                // const newArray = [...state.results];
                // newArray.splice(id,1);
    
                const updatedArray = state.results.filter(result => result.id !== action.resultId);
    
                return {
                    ...state,
                    results:updatedArray
                }
    
        }
    
        return state;
    };
    
    
    export default reducer;
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Vinayak Bagaria    6 年前

    结果还原器中的初始状态是 result . 把它改成 results