ReactJS。操作已成功调度但未到达减速器

时间:2020-05-22 11:14:29

标签: javascript reactjs redux

在componentDidMount()方法中,我调度了一个异步操作,该操作从另一个API提取某些数据。在redux开发工具中,调度了获取数据成功方法,并且该方法具有从响应中检索到的正确有效负载。但是,此操作似乎未达到reducer,因为我的redux存储中的状态未更改。我将console.log()注入到Reducer中,并发现未达到Reducer。

我查看了其他相关帖子,但找不到任何解决方案。

我已经提供了相关的代码段,将不胜感激!我正在使用thunk作为中间件。

//index.js

const rootReducer = combineReducers({
  search: searchBarReducer,
});

const composeEnhancers = process.env.NODE_ENV === 'development' ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : null || compose;

const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

const app = (
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>
);

ReactDOM.render(app, document.getElementById("root"));
registerServiceWorker();

//action creator 

export const suggestionsInit = (filter) => {
  console.log("[suggestionsInit]")
  return (dispatch) => {
    let result = [];
    axios
      .get("")
      .then((response) => {
        response.data.forEach((element) => {
          result.push(element.moduleCode);
        });
        dispatch(fetchSuggestionsSuccess(result));
      })
      //
  };
};

export const fetchSuggestionsSuccess = (data) => {
  return {
    type: actionTypes.FETCH_SUGGESTIONS_SUCCESS,
    data: data,
  };
};

//reducer

const initialState = {
    modules: [],
    //
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.SEARCHBAR_INT: 
        return {
            ...state,
            modules: action.data
        }
        default: return state;
    }
}

//associated component

componentDidMount() {
    console.log("[componentDidMount]");
    this.props.dispatchSuggestionsInit("modules");
  }

...
//after class body 

const mapStateToProps = (state) => {
  return {
    modules: state.search.modules,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    dispatchSuggestionsInit: (filter) => dispatch(actions.suggestionsInit(filter)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(SearchBar, axios));
//with error handler is just another higher order component and it does not affect the functionality.

1 个答案:

答案 0 :(得分:0)

在减速器文件中,您应该正在侦听/检查是否已成功调度,原因是当您调度成功数据时,您正在调度的动作类型为actionTypes.FETCH_SUGGESTIONS_SUCCESS,而不是INIT。 >

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.FETCH_SUGGESTIONS_SUCCESS:
      return {
        ...state,
        modules: action.data
      };
    default: return state;
  }
};