反应Native Connect Redux Action&Reducer

时间:2018-12-26 20:28:27

标签: reactjs react-native redux react-redux redux-thunk

我一直在尝试将Redux Action和Reducer连接到我的组件。但这似乎无法正常工作。

当前,当我调用我的动作时,它确实到达了该动作,但没有移到我的减速器上。我想我在这里遗漏了一些东西,但是很难找出问题所在。

有人可以帮我解决这个问题吗?

谢谢。

这是我的动作:

export const getItem = () => {
  return (dispatch, getState) => {
    debugger;
    dispatch({
      type: 'API_REQUEST',
      options: {
        method: 'GET',
        endpoint: `18.222.137.195:3000/v1/item?offset=0`,
        actionTypes: {
          success: types.GET_ITEM_SUCCESS,
          loading: types.GET_ITEM_LOADING,
          error: types.GET_ITEM_SUCCESS
        }
      }
    });
  };
};

这是我的减速机:

export const initialState = {
 getItem: {}
};

const registerItemReducer = (state = initialState, action) => {
 switch (action.type) {
  case types.GET_ITEM_LOADING:
   debugger;
   return { ...state, loading: true, data: null };

  case types.GET_ITEM_SUCCESS:
   debugger;
   return { ...state, loading: false, getItem: action.data};

  case types.GET_ITEM_ERROR:
   debugger;
   return { ...state, loading: false, error: action.data};

  default: {
   return state;
  }
 }
}
export default registerItemReducer;

这是我的商店:

/* global window */
import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/es/storage'; // default: 
localStorage if web, AsyncStorage if react-native
import thunk from 'redux-thunk';
import reducers from '../reducers';

// Redux Persist config
const config = {
  key: 'root',
  storage,
  blacklist: ['status'],
};

const reducer = persistCombineReducers(config, reducers);

const middleware = [thunk];

const configureStore = () => {
  const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && 
window.__REDUX_DEVTOOLS_EXTENSION__(),
    compose(applyMiddleware(...middleware)),
  );

  const persistor = persistStore(
    store,
    null,
    () => { store.getState(); },
  );

  return { persistor, store };
};

export default configureStore;

最后这是我的具有“连接”零件和componentDidMount的组件:

componentDidMount() {
    this.props.getItem();
 }

const mapStateToProps = state => ({
  registerItem: state.registerItem || {},
});

const mapDispatchToProps = {
  getItem: getItem
};

export default connect(mapStateToProps, mapDispatchToProps)(RegisterItemComponent);

1 个答案:

答案 0 :(得分:0)

您的减速器的registerItem名称是吗?减速器具有两个状态getItem和loading。但是在下面的代码中,您正在调用state.registerItem。看起来实际状态和映射状态之间有些不匹配。

在下面的代码中,尝试打印状态值,它将帮助您导航到要查找的确切参数。

在现有代码中添加以下行以进行调试:

const mapStateToProps = state => ({
 console.log("State of reducer" + JSON.stringify(state));
 registerItem: state.registerItem || {},
});