【问题标题】:How to add new object into existing state using react and redux saga如何使用 react 和 redux saga 将新对象添加到现有状态
【发布时间】:2019-05-24 11:36:50
【问题描述】:

我有一个包含这样信息的对象。

export const initialSettings = {
  id: '01',
  name: '',
  lat: '',
  long: '',
  adressLine1: '',
  adressLine2: '',
  city: '',
  state: '',
  country: '',
  zipcode: '',
  status: '',
  lastCommunicateDateTime: '',
    {
      PatientID: '1',
      FirstName: 'Manav',
      LastName: 'Pandya',
      DateOfBirth: '',
      MobileNo: '',
      orders: [
        {
          orderId: '01',
          pickupCode: 'XYZ456',
          totalAmount: 40.0,
          taxPercentage: 3,
          insuranceAmount: 20.0,
          totalCoPayAmount: 40.0,
          totalPaidAmount: 40.0,
          totalDueAmount: '',
          paymentDueDate: '',
          items: [
            {
              itemId: '01',
              image: 'https://via.placeholder.com/30',
            }
          ]
        }
      ]
    },
    {
      PatientID: '2',
      FirstName: 'Manav',
      LastName: 'Pandya',
      DateOfBirth: '',
      MobileNo: '',
      orders: [
        {
          orderId: '01',
          pickupCode: 'XYZ456',
          totalAmount: 40.0,
          taxPercentage: 3,
          insuranceAmount: 20.0,
          totalCoPayAmount: 40.0,
          totalPaidAmount: 40.0,
          totalDueAmount: '',
          paymentDueDate: '',
          items: [
            {
              itemId: '01',
              image: 'https://via.placeholder.com/30',
            }
          ]
        }
      ]
    }
  ]
};

但是当我尝试使用减速器添加新项目时,旧状态被删除并且不会得到正确的状态

每当我发布与以前的对象不同的详细信息的表单时,都会删除不适当的新对象

我的请求减速器看起来像这样。

 case 'add':
      return Map({
        state: {
          ...state, // old object should remains same
          patients: [state.patients, action.payload] // new item
        }
      });

【问题讨论】:

  • 您需要在reducer中传播患者名单:patients: [...state.patients, action.payload]

标签: reactjs react-redux redux-saga reducers


【解决方案1】:

在reducer中应该是这样的:

case 'add':
    return {
        ...state, // old object should remains same
        patients: [state.patients, action.payload] // new item
    };

【讨论】:

    【解决方案2】:

    你应该添加减速器;

    case 'add':
      return {
        ...state,
        error: false,
        loading: false,
        data: state.data.concat(action.data), }
    

    之后,您需要选择器将数据从选择器发送到状态;

    export const getDataDetail = state => getDataDetail(state)?.data;
    

    最后一个选项是你应该调用你的更新数据。你应该使用

    componentWillRecieve(nextProps) {
      ...... use your data match with nextProps and props
     if(nextData && nextData !== this.props.yourData) {
         this.setState({ data : nextData }) }}
    

    应该是这样的。

    【讨论】:

    • 这对我来说不是正确的解决方案,我使用的是 immutablejs 的 Map(),我不需要调用 componentWillReceive(),我只需要专门针对 reducer 的解决方案,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2018-03-20
    • 1970-01-01
    • 2021-02-07
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多