в billDetailForm, как удалить последнюю строку из таблицы сведений без удаления других строк с введенными значениями - PullRequest
0 голосов
/ 28 февраля 2020

Я пытаюсь удалить последнюю запись таблицы, но вместо нее также удаляются полные записи записей.

Я использую селектор значений формы для вычисления промежуточных итогов. Вот мой код с наблюдениями.

const selector = formValueSelector ('bill');

 class Detail extends Component{

       //When I remove a specific field with specify index all fields with subtotal calculated 
          //and showed are also deleted. 
      componentDidUpdate(prevProps, index) {
           if (this.props.isSubtotal !== prevProps.isSubtotal) {
               this.props.dispatch(
                //Changing subtotal field from field array with dynamic index
            change('bill', `detail[${this.props.index}].subtotal`, this.props.isSubtotal)
                 );
                    }
                     } 

//Here I'm rendering my Detail Component

    render(){

        const{detailItem,index,fields,isSubtotal} = this.props;

         return(


            <tr key={index}>

             <td>
               <Field 
                  id={`${detailItem}._id`}
                  name={`${detailItem}.quantity`}
                  type='number'
                  component= {UtilityQuantity}
                  placeholder= '...quantity'
                    />
                  </td>

      <td>
        <Field 
          id={`${detailItem}._id`}
          name={`${detailItem}.product.code`}
          type="number"
          component= {UtilityCode}
          placeholder='...Product's code'
          />
         </td>
          <td>
           <Field 
             id={`${detailItem}._id`}
             name={`${detailItem}.product.name`}
             type="text"
             component= {UtilityName}
             placeholder='...Product's name'
             />
             </td>
              <td>
               <Field 
                id={`${detailItem}._id`}
                name={`${detailItem}.product.price`}
                type="number"
                component= {UtilityPrice}
                placeholder= '...Price'
                // label = "Product's price" 
                 />
                </td>

             <td>
              <Field 
               id={`${detailItem}._id`}
               name={`${detailItem}.subtotal`}
               component= {UtilitySubTotal}
               placeholder= '...subtotal'

                >
              {isSubtotal}
                </Field> 
                 </td>

                  </tr>


               );


        }

        }

 //In this component I'm rendering the Detail class component

              const RenderDetail = ({fields, meta: { error,submitFailed}}) => (

                 <dl>
                 <b> Detail: </b>
                  <dt>
                   <button type="button" className= 'btn btn-primary' onClick={() => 
                  fields.push()}>Add Detail</button>
                        {submitFailed && error && <span>{error}</span>}
                        </dt>
                      <div className='table-responsive'>
                       <table className='table table-striped table-sm'>
                        {/*DEFINING THE COLUMNS*/}
                        <thead>
                           <tr>
                           <th>Quantity</th>
                           <th>Product's code</th>
                           <th>Product's name</th>
                           <th>Product's price</th>
                           <th>Subtotal</th>


                            </tr>
                           </thead>
      {/*DEFINING THE ROWS INCLUDING THE BODY CONTAINING ROWS*/}
            <tbody>
                  { fields.map((registerDetail, index) =>

        {/*Here I'm rendering every detail Item*/}
           <Detail detailItem={registerDetail} fields={fields} index={index} key={index} />

             )
             }
             </tbody>
             </table>
             </div>

          {error && <dt className="error">{error}</dt>} 
           <button className='btn btn-light mr-2'
              type="button"
              title="Remove Detail"
              onClick={() =>{
            //HERE I'm defining the last element of field array
                        let selectedIndex = fields.length - 1;
              //HERE IS THE KEY LINE. Selected field value from field array is deleted, but 
                  //fields value with inserted data are deleted too. 
                          fields.remove(selectedIndex);

                          }}>

                DELETE Detail       
                </button>
                  </dl> 

                 );
                  }
                  //Following lines not important for the problem. These ones are initializating 
                   //component on redux form
            Detail = reduxForm({

                       form: 'bill',
                          validate
                        })(Detail);

                 //Binding Detail Component to actions and redux store
                  Detail = connect((state,props,fields) =>{

              //Defining entry data to calculate subtotal automatically with out using redux

                  const quantity = selector(state,`${props.detailItem}.quantity`);

                       const price = selector(state,`${props.detailItem}.product.price`);

                return{

             //RETURNING calculated subtotal in each record
          isSubtotal: quantity * price

           }
                     },{})(Detail) 

Ожидается следующее поведение: a, b и c - мои строки, добавленные в деталь.

                      a: {quantity: 30, code: null, name: null, price: 20, subtotal: 600}
                      b: {quantity: 10, code: null, name: null, price: 10, subtotal: 100}
                      c: {quantity: null, code: null, name: null, price: null, subtotal: null}

индекс c - это fields.length - 1 значение.

Я должен удалить c и должен выглядеть так:

                      a: {quantity: 30, code: null, name: null, price: 20, subtotal: 600}
                      b: {quantity: 10, code: null, name: null, price: 10, subtotal: 100}

Однако реальное поведение приложения было следующим:

                      a: {quantity: 30, code: null, name: null, price: 20, subtotal: 600}
                      b: {quantity: 10, code: null, name: null, price: 10, subtotal: 100}
                      c: {quantity: null, code: null, name: null, price: null, subtotal: null}

Я удаляю c, и реальный вывод таков:

                                 //EMPTY VALUES, I can't see nothing

В чем проблема ?, Если я удалил последняя строка из таблицы, строки со вставленными данными также удалены.

Как я могу решить эту проблему, любое решение?

Все, что я хочу, это удалить последнюю строку из формы таблицы, которая называется деталь без удаления остальные строки заполнены данными.

...