2017-12-23 3 views
0

React 16 폼을 만들었습니다. 디스플레이 레코드, 레코드 추가, 레코드 삭제를 완료했습니다. 레코드 업데이트에 관해서는 대신 새 레코드가 삽입됩니다. 동일한 레코드 값을 전달하는 경우 아무 일도 발생하지 않습니다. 업데이트 항목에 대해서는 handleSubmit의 부분을 if 부분에 표시하고 항목을 추가하려면 부분을 else 부분으로 확인했습니다. 여기에서 변경해야 할 부분은 무엇입니까?React 16 폼 업데이트 작업은 레코드를 업데이트하는 대신 새 레코드를 만듭니다.

import React, { Component } from "react"; 
import { 
    Form, 
    FormGroup, 
    //ControlLabel, 
    FormControl, 
    Col, 
    Button, 
    // PageHeader, 
    // Row, 
    // Grid, 
    Modal, 
    ButtonToolbar, 
    Table 
} from "react-bootstrap"; 

//const Dashboard = ({ email }) => (

class Dashboard extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     name: "", 
     description: "", 
     amount: "", 
     date: "", 
     show: false, 
     formdata: [] 
    }; 

    this.handleSubmit = this.handleSubmit.bind(this); 
    this.handleInputChange = this.handleInputChange.bind(this); 
    this.showModal = this.showModal.bind(this); 
    this.hideModal = this.hideModal.bind(this); 
    this.showEditModal = this.showEditModal.bind(this); 
    } 

    showModal() { 
    this.setState({ show: true }); 
    } 

    showEditModal(event, i) { 
    const recordToEdit = this.state.formdata.filter((item, index) => { 
     return index === i; 
    })[0]; 

    this.setState({ 
     show: true, 

     name: recordToEdit.name, 
     description: recordToEdit.description, 
     amount: recordToEdit.amount, 
     date: recordToEdit.date 
    }); 
    } 

    hideModal() { 
    this.setState({ 
     show: false, 
     name: "", 
     description: "", 
     amount: "", 
     date: "" 
    }); 
    } 

    handleInputChange(event) { 
    // update the input that changed 
    this.setState({ 
     [event.target.name]: event.target.value 
    }); 
    } 

    handleSubmit(event) { 
    const formItem = { 
     name: this.state.name, 
     description: this.state.description, 
     amount: this.state.amount, 
     date: this.state.date 
    }; 

    if (
     this.state.name === "" || 
     this.state.amount === "" || 
     this.state.date === "" 
    ) { 
     alert("Please fill mandatory filed"); 
    } else { 
     if (this.state.formdata.filter(item => item.name === formItem.name).length > 0) { 
     // update item 
     this.setState(prevState => ({ 
      formdata: prevState.formdata.map(item => { 
      if (item.name === formItem.name) 
       return formItem; 
      else 
       return item; 
      }) 
     })); 

     } else { 
     // add new item 
     this.setState(prevState => ({ 
      formdata: prevState.formdata.concat(formItem) 
     })); 

     } 

     alert("form submited: "); 

     this.setState({ 
     name: "", 
     description: "", 
     amount: "", 
     date: "" 
     }); 
    } 
    event.preventDefault(); 
    } 

    deleteExpense(i) { 
    alert("are you sure you want to Delete this item ?"); 
    this.setState({ 
     formdata: this.state.formdata.filter((item, index) => { 
     return index !== i; 
     }) 
    }); 
    } 

    render() { 
    return (
     <div> 
     <p>Welcome</p> 

     <ButtonToolbar> 
      <Button bsStyle="primary" onClick={this.showModal}> 
      Add Expenses 
      </Button> 
      <Table striped bordered condensed hover> 
      <thead> 
       <tr> 
       <th>name</th> 
       <th>description</th> 
       <th>amount</th> 
       <th>date</th> 
       <th>Action</th> 
       </tr> 
      </thead> 
      <tbody> 
       {this.state.formdata.map((item, i) => (
       <tr key={i}> 
        <td>{item.name}</td> 
        <td>{item.description}</td> 
        <td>{item.amount}</td> 
        <td>{item.date}</td> 
        <td> 
        <Button bsStyle="warning" onClick={(e) => this.showEditModal(e, i)}> 
         Update 
        </Button> 
        <Button 
         bsStyle="danger" 
         onClick={() => this.deleteExpense(i)} 
        > 
         Delete 
        </Button> 
        </td> 
        <td /> 
       </tr> 
      ))} 
      </tbody> 
      </Table> 
      <Modal 
      {...this.props} 
      show={this.state.show} 
      onHide={this.hideModal} 
      dialogClassName="custom-modal" 
      > 
      <Modal.Header closeButton> 
       <Modal.Title 
       id="contained-modal-title-lg " 
       className="text-center" 
       > 
       Add Expenses 
       </Modal.Title> 
      </Modal.Header> 
      <Modal.Body> 
       <Form horizontal onSubmit={this.handleSubmit}> 
       <FormGroup controlId="formHorizontalEmail"> 
        <Col smOffset={4} sm={4}> 
        <FormControl 
         type="Text" 
         placeholder="name" 
         name="name" 
         value={this.state.name} 
         onChange={this.handleInputChange} 
        /> 
        </Col> 
       </FormGroup> 
       <FormGroup controlId="formHorizontalPassword"> 
        <Col smOffset={4} sm={4}> 
        <FormControl 
         type="description" 
         placeholder="description" 
         name="description" 
         value={this.state.description} 
         onChange={this.handleInputChange} 
        /> 
        </Col> 
       </FormGroup> 
       <FormGroup controlId="formHorizontalPassword"> 
        <Col smOffset={4} sm={4}> 
        <FormControl 
         type="amount" 
         placeholder="amount" 
         name="amount" 
         value={this.state.amount} 
         onChange={this.handleInputChange} 
        /> 
        </Col> 
       </FormGroup> 
       <FormGroup controlId="formHorizontalPassword"> 
        <Col smOffset={4} sm={4}> 
        <FormControl 
         type="date" 
         placeholder="date" 
         name="date" 
         value={this.state.date} 
         onChange={this.handleInputChange} 
        /> 
        </Col> 
       </FormGroup> 

       <FormGroup> 
        <Col smOffset={5} sm={4}> 
        <Button type="submit" bsStyle="primary"> 
         Add 
        </Button> 
        </Col> 
       </FormGroup> 
       </Form> 
      </Modal.Body> 
      </Modal> 
     </ButtonToolbar> 
     </div> 
    ); 
    } 
} 
export default Dashboard; 

답변

0

실수를 발견 할 수 없습니다. 이런 상태를 확인하면 도움이됩니까? formdata.nameindexOf을 수행합니다. 상태에 동일한 이름의 항목이 없으면 인덱스는 -1이됩니다. 이처럼 상태를 가능한 오류에 대한 가능성을 최소화하기 위해 prevState를 계속 업데이트 할 경우

// find item in state with same name 
const index = this.state.formdata.map((item) => { 
    return item.name; 
}).indexOf(formItem.name); 

if (index >= 0) { 
    // update item 
    const formdata = this.state.formdata; 
    formdata[index]= formItem; 
    this.setState({ formdata }); 
} else { 
    // insert new item 
    this.setState(prevState => ({ 
    formdata: prevState.formdata.concat(formItem) 
    })); 
} 

또는 :

// update item 
    this.setState(prevState => { 
    const {formdata} = prevState; 
    formdata[index] = formItem; 
    return { formdata } 
    } 
+0

안녕, 내 코드와 코드를 교체 한 여전히 동일하게 동작합니다. { // 업데이트 항목 this.setState (prevState => ({ formdata : prevState.formdata) 항목을 업데이트 할 때 this.state.formdata.filter (item.name === formItem.name) .length> .map (item => { if (item.name === formItem.name) return formItem; else 반환 항목; }} })))))); } 다른 { // 새 항목 추가 this.setState (prevState => ({ formdata : prevState.formdata.concat (FormItem의) })); } –