Как я могу удалить последнюю строку из таблицы в форме без других строк с вставленными данными? - PullRequest
1 голос
/ 29 февраля 2020

Я новичок в этом форуме. У меня проблема. Когда я удаляю последнюю строку из таблицы, удаляются и другие строки с вставленными данными.

Вот код, который вы должны увидеть с наблюдениями:

      const selector = formValueSelector('bill'); //initializating a selector. bill is the name of 
                                                   // the form.

Затем чуть ниже эта строка кода:

                      const selector = formValueSelector('bill');

У меня есть компонент класса с именем Detail:

             class Detail extends Component{

                    //In the FOLLOWING LINES I'm changing props of calculated subtotal called as 
                    //"isSubtotal"
             componentDidUpdate(prevProps, index) {
                   if (this.props.isSubtotal !== prevProps.isSubtotal) {
                        this.props.dispatch(
                     //bill is the name of the form. Changing subtotal detail with dynamic index.
                      //this.props.index is the dynamic index and this.props.isSubtotal is calculated 
                      //value
                change('bill', `detail[${this.props.index}].subtotal`, this.props.isSubtotal)
                   );
                    }
                    } 



                         //HERE I'm rendering Detail's 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'
                                // label = "Quantity" 
                                 />
                                </td>


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

                                      <td>
                                       <Field 
                                        id={`${detailItem}._id`}
                                        name={`${detailItem}.product.name`}
                                        type="text"
                                        component= {UtilityName}
                                        placeholder='...product's name'
                                        // label = "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'
                                   // label = "Subtotal" 
                                     >
                                    {isSubtotal}
                                     </Field> 
                                      </td>
                                      </tr>
                                        );
                                         }

                                          }

Вот RenderDetail, который содержит DetailComponent при его итерации:

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


                                 return(

                                    <dl>
                                    <b> Detail: </b>
                                     <dt>
                               {/*When Clicking on Add Detail Add each row to the table "detail"*/}
                              <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'>
                               {/*Here I'm declaring the columns of the table*/}
                                  <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>
                                       <tbody>
                   {/*HERE inside tbody tag I'm getting fields from every detail item*/}

                           { fields.map((registerDetail, index) =>

                           {/*Detail is the class Component*/}
                  <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={() =>{

                         //THIS FOLLOWING line I'm assign the index from last row to selectedIndex

                             let selectedIndex = fields.length - 1;

                              //HERE IS THE KEY LINE you must pay attention

                                 fields && fields.remove(selectedIndex);

                              }}>

                               Delete Detail

                              </button>

                               </dl> 

                                 )};

Здесь я инициализирую свой компонент детализации с использованием формы редукса:

                    //INITIALIZATING DETAIL COMPONENT FORM

                       Detail = reduxForm({

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

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

                             Detail = connect((state,props,fields) =>{


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

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

                                return{

                                  isSubtotal: quantity * price

                                    }
                                  },{})(Detail) 

Я объясню вам, как работает таблица. Когда я нажимаю добавить детали, я добавляю строку. например, я добавил 5 строк.

      And e.g I insert 10 in quantity and 20 in price on first row and I've got 200 in subtotal field. Subtotal is not editable. It's calculated.

         Now, in second row I insert 10 in quantity and 10 in price and I've got 100 in subtotal. The other rows are empty. The data form should be like this:

                                row 1 : {quantity: 10, product: {code: 13321, name: "product 1", 
                                       price: 20}, subtotal: 200},

                                row 2 : {quantity: 10, product: {code: 12222, name: "product 2", 
                                            price: 10}, subtotal: 100}

                                row 3 : {quantity: null, product: {code: null, name: null, 
                                                    price: null}, subtotal: null}


                                row 4 : {quantity: null, product: {code: null, name: null, 
                                                    price: null}, subtotal: null}


                                row 5 : {quantity: null, product: {code: null, name: null, 
                                                    price: null}, subtotal: null}

 the expected behavior is When I'm deleting last row, row 5 in this case, the data I'm showing on screen should be like this:

                                row 1 : {quantity: 10, product: {code: 13321, name: "product 1", 
                                       price: 20}, subtotal: 200},

                                row 2 : {quantity: 10, product: {code: 12222, name: "product 2", 
                                            price: 10}, subtotal: 100}

                                row 3 : {quantity: null, product: {code: null, name: null, 
                                                    price: null}, subtotal: null}


                                row 4 : {quantity: null, product: {code: null, name: null, 
                                                    price: null}, subtotal: null}

Но реальный результат - когда я удалил последнюю строку. В этом случае строка 5, строка 1 и строка 2 также удаляются. И у меня есть следующий вывод:

                                 row 3 : {quantity: null, product: {code: null, name: null, 
                                                    price: null}, subtotal: null}


                                row 4 : {quantity: null, product: {code: null, name: null, 
                                                    price: null}, subtotal: null}

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

Может кто-нибудь придумать решение этой проблемы?

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

1 Ответ

0 голосов
/ 01 марта 2020

Немного сложно понять твой код. Лучшим способом показать свою работу будет repl.it для быстрого понимания. В любом случае, я думаю, что вы должны использовать вместо этого разделение, чтобы удалить целевой массив с индексом.

field.splice(selectedIndex, 1);
...