redux 使用获取的数据更新状态,但当尝试console.log时,它给出“undefined”

oxf4rvwz  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(113)

当我在渲染或更改某些依赖项时获取数据时,它会在Redux存储中正确更新,但当console. logging时,它会显示“unifined”。
我正在开发预订系统,并希望获取已经预订的时间在指定的日子

/// Fetch data on render the component and try to console.log
     useEffect(() => {
    axios
      .get(
        `http://localhost/healthboyz/index.php/booked/${
          formData.doctor_id
        }/${moment(formData.date).format('YYYY-MM-DD')}`
      )
      .then((res) => setBookedHrs(res.data))
      .then(() => console.log(bookedHrs))
      .catch((e) => console.log(e));}, 
    [formData.doctor_id, formData.date]);
/// Hours reducer 
 const hoursReducerDefaultState: {
  bookedHrs: string[];
} = {
  bookedHrs: [],
};

export const hoursReducer = (
  state = hoursReducerDefaultState,
  action: {
    type: string;
    data: string[];
  }
) => {
  switch (action.type) {
    case 'SET_BOOKED_HRS':
      return [...action.data];
    default:
      return state;
  }
};
pbgvytdp

pbgvytdp1#

这里的问题实际上是关于如何在Redux中设置状态:
假设hoursReducer负责整个hoursReducerDefaultState,即:

type HoursReducer = {
  bookedHrs: string[];
};

 const hoursReducerDefaultState: HoursReducer = {
  bookedHrs: [],
};

然后,您需要将Redux状态设置为您要更新的更新状态:

export const hoursReducer = (
  state = hoursReducerDefaultState,
  action: {
    type: string;
    data: string[];
  }
) => {
  switch (action.type) {
    case 'SET_BOOKED_HRS':
      // Remember to include the previous state using the "spread" operator
      return {
        ...state,
        bookedHrs: action.data
      }
    default:
      return state;
  }
};

注意:我还假设你想完全替换bookedHrs的值。

相关问题