如何使用react和redux saga将新对象添加到现有状态

时间:2018-12-26 06:14:58

标签: reactjs react-redux redux-saga reducers

我有一个对象,上面有这样的信息。

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
        }
      });

2 个答案:

答案 0 :(得分:0)

在reducer中应该是这样的:

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

答案 1 :(得分:0)

您应该添加reducer;

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

之后,您需要选择器将数据从选择器发送到状态; <​​/ p>

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 }) }}

应该是这样。