You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Redux-Sauce拉取数据后无法更新state,代码哪里出错了?

错误原因

  1. mapDispatchToProps 参数使用错误:该函数的第一个入参为 dispatch 而非 state
  2. 你返回的 actions 只是纯action creator集合,没有通过 dispatch 包裹,调用时仅会返回action对象,不会发送给reducer,自然不会触发state更新
  3. reducer逻辑存在遗漏,请求完成后没有重置loading状态

修复方案

1. 修改HomeContainer.js

首先从redux导入bindActionCreators用于批量包裹action creator:

import { bindActionCreators } from "redux";

然后修正mapDispatchToProps的实现:

// 原错误写法
// const mapDispatchToProps = (state, ownProps) => {
//   return {
//     actions: Creators
//   };
// };

// 修正后的写法
const mapDispatchToProps = (dispatch) => {
  return {
    actions: bindActionCreators(Creators, dispatch)
  }
}

2. 修改reducer.js中的handler逻辑,补充loading重置

export const fetchDataRequest = (state = initialState, action) => {
  return { ...state, loading: true, data: [], error: false };
};

export const fetchDataSuccess = (state = initialState, action) => {
  // 新增loading重置为false
  return { ...state, loading: false, data: action.payload, error: false };
};

export const fetchDataFail = (state = initialState, action) => {
  // 新增loading重置为false
  return { ...state, loading: false, data: null, error: action.error };
};

调用说明

修复后你原本的调用逻辑不需要改动,调用actions.fetchDataRequest()、actions.fetchDataSuccess(data)、actions.fetchDataFail(error)时会自动触发dispatch,reducer会接收到action并更新对应state,组件就能拿到最新的iTunesData数据。

内容的提问来源于stack exchange,提问作者user14467240

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:06:05