繁体   English   中英

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

[英]ReactJS. action is successfully dispatched but not reaching reducer

在 componentDidMount() 方法中,我调度了一个从另一个 API 获取一些数据的异步操作。 在 redux 开发工具中,将调度获取数据成功方法,并从响应中检索到正确的有效负载。 但是,这个动作似乎没有到达减速器,因为我的 redux 商店中的 state 没有改变。 我在减速器中注入了 console.log() 并注意到减速器没有到达。

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

我已经提供了相关的代码片段,将不胜感激。 我使用 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.

在您的减速器文件中,您应该侦听/检查调度的成功案例,原因是您在调度成功数据时使用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;
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM