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

为何React Redux中props返回getShifts动作函数而非数据?

解决Redux Thunk中组件Props仅显示Action函数的问题

看起来你遇到的问题是组件的props里只有getShifts这个action函数,没有从Redux Store中获取到的shifts数据,这是因为你还没把Store中的状态映射到组件的props里。让我一步步帮你解决这个问题:

1. 为什么props里只有getShifts函数?

你在使用connect的时候,第一个参数传了null:

export default connect(null, MapDispatchToProps)(StaffRota);

connect的第一个参数是mapStateToProps,它的作用是把Redux Store中的状态数据映射到组件的props中。你传了null,意味着没有任何Store状态被传入组件,所以props里只有第二个参数mapDispatchToProps提供的action函数。

2. 优化Reducer的状态结构

当前你的Reducer只返回了start_time,这会覆盖整个state,而且结构不够清晰。我们应该维护一个包含数据、错误状态的完整结构:

import { GET_STAFF_SHIFTS, SHIFTS_LOAD_FAIL } from '../actions';

// 初始化状态:包含shifts数据、错误标记
export default function(state = { shifts: null, hasError: false }, action) {
  switch(action.type){
    case GET_STAFF_SHIFTS:
      // 用展开运算符合并状态,保留原有其他字段
      return { ...state, shifts: action.payload, hasError: false };
    case SHIFTS_LOAD_FAIL:
      return { ...state, hasError: true, shifts: null };
    default:
      return state;
  }
}

另外,记得在combineReducers中给这个Reducer起明确的名字(比如staffShifts),这样后面才能正确从state中获取数据:

// 假设你的store配置文件
import { combineReducers } from 'redux';
import staffShiftsReducer from './staffShiftsReducer';

const rootReducer = combineReducers({
  staffShifts: staffShiftsReducer // 这里的key就是state中的属性名
});

export default rootReducer;

3. 添加mapStateToProps映射Store状态到Props

在你的组件中添加mapStateToProps函数,把Store中的shifts数据和错误状态映射到组件props:

// 组件代码中添加这个函数
function mapStateToProps(state) {
  // 这里的state.staffShifts对应你在combineReducers中给Reducer起的名字
  return {
    staffShifts: state.staffShifts.shifts,
    shiftsLoadError: state.staffShifts.hasError
  };
}

// 修改connect,传入mapStateToProps
export default connect(mapStateToProps, MapDispatchToProps)(StaffRota);

4. 统一使用Action类型常量(可选但推荐)

你已经定义了GET_STAFF_SHIFTS常量,但在dispatch的时候用了字符串字面量,最好统一使用常量,避免拼写错误:

// Action中的then部分修改为
.then(response => dispatch({ type: GET_STAFF_SHIFTS, payload: response }) )

5. 在组件中使用映射后的状态

现在你可以在renderPosts中打印完整的props,并且根据状态渲染内容:

renderPosts(){
  console.log('完整Props:', this.props);
  // 根据状态渲染不同内容
  if (this.props.shiftsLoadError) {
    return <div>加载排班失败,请稍后重试</div>;
  }
  if (!this.props.staffShifts) {
    return <div>正在加载排班...</div>;
  }
  // 有数据时渲染
  return (
    <div className="shifts-list">
      {this.props.staffShifts.map(shift => (
        <div key={shift.id} className="shift-item">
          <p>开始时间: {shift.start_time}</p>
          {/* 其他排班信息 */}
        </div>
      ))}
    </div>
  );
}

做完这些修改后,你再打印this.props,就能看到staffShifts、shiftsLoadError和getShifts函数了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:15:07