编辑和删除功能无法正常使用

时间:2019-09-12 01:40:04

标签: reactjs react-router

我有一个表单,当我提交该表单的详细信息时,它将重定向到下一页,并在其中显示日期。那里我自己有两个按钮可以编辑和删除。这两个功能不起作用。 你能帮我吗?在此先感谢。

import React, { Component } from 'react';
import axios from "axios";
import {withRouter} from 'react-router';

 class App extends Component {
    constructor(props) {
        super(props)

        this.state = {
             data:[],
              objEdit:obj
                   }
            }


// handleInput(e){
//     this.state.objEdit[e.target.name] = e.target.value
//     this.setState({objEdit:this.state.objEdit})
// }

handleInput(e){

    this.setState({
        objEdit:{...this.state.objEdit, [e.target.name] : e.target.value}
    })

}

updateUser = () =>{
    console.log(this.state.objEdit)
    const objEdit = {...this.state.objEdit, id: null};
    axios.post("http://localhost:3000/data/", objEdit).then(()=>{
     this.props.history.push('/Form')
         }).catch((error)=>{
        console.log("Error Occured")
    })
} 
    render() {
        return (
            <div>

                <div className="col-sm-4">

                    <form>
                    <div className="form-group">
                        <label htmlFor="fname">First Name</label>
                        <input type="text" className="form-control" name="fname" placeholder="Enter First Name" value={this.state.objEdit.fname} onChange={(e)=>{this.handleInput(e)}}/>
                    </div>
                    <div className="form-group">
                        <label htmlFor="lname">Last Name</label>
                        <input type="text" className="form-control" name="lname" placeholder="Enter First Name" value={this.state.objEdit.lname} onChange={(e)=>{this.handleInput(e)}}/>
                    </div>
                    <div className="form-group">
                        <label htmlFor="tel">Tel</label>
                        <input type="text" className="form-control" name="tel" placeholder="Tel" value={this.state.objEdit.tel} onChange={(e)=>{this.handleInput(e)}}/>
                    </div>
                    <div className="form-group">
                        <label htmlFor="address">Address</label>
                        <input type="text" className="form-control" name="address" placeholder="Enter First Name" value={this.state.objEdit.address} onChange={(e)=>{this.handleInput(e)}}/>
                    </div> 
                    <div className="form-group">
                        <label htmlFor="fname">City</label>
                        <input type="text" className="form-control" name="city" placeholder="Enter First Name" value={this.state.objEdit.city} onChange={(e)=>{this.handleInput(e)}}/>
                    </div>
                    <div className="form-group">
                        <label htmlFor="state">State</label>
                        <input type="text" className="form-control" name="state" placeholder="Enter First Name" value={this.state.objEdit.state} onChange={(e)=>{this.handleInput(e)}}/>
                    </div> 
                    <div className="form-group">
                        <label htmlFor="zip">Zip</label>
                        <input type="text" className="form-control" name="zip" placeholder="Enter First Name" value={this.state.objEdit.zip} onChange={(e)=>{this.handleInput(e)}}/>
                    </div>    
                    <button type="button" className="btn btn-primary" onClick={this.updateUser}>Submit</button>
                    </form>

                </div>

                </div> 

            // </div>
        )
    }
}
export default withRouter(App);

这里有我的“编辑和删除”功能。我有两个按钮可以进行“编辑”和“删除”。这两个功能不起作用。

 let obj={
        fname:"",
        lname:"",
        tel:"",
        address:"",
        city:"",
        state:"",
        zip:'',
        id:''
    }

    import React, { Component } from 'react'
    import axios from "axios";
    import { Link } from 'react-router-dom';



        class Form extends Component {

            constructor(props) {
                super(props)

                this.state = {
                     data:[],

                    }
                    }
                    componentDidMount(){
                        fetch('http://localhost:3000/data')
                        .then(response => response.json())
                        .then(user => this.setState({data:user}))
                    }
                    editUser=(obj,index)=>{
                        console.log(obj,index)
                        this.setState({objEdit:obj})
                    }
                    deleteUser=(i)=>{
                        console.log("deleteUser called",i)
                        axios.delete("http://localhost:3000/data/"+this.state.data[i].id).then(res=>{
                            console.log()
                        }).catch((error)=>{
                            console.log("Error Occured")
                        })
                    }

          render() {
            return (
              <div>
                 <div className="row">
                            <div className="col-sm-8">
                            <table className="table">
                            <thead>
                                <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Tel</th>
                                <th>Address</th>
                                <th>City</th>
                                <th>State</th>
                                <th>Zip</th>
                                <th>Edit</th>
                                <th>Delete</th>
                                </tr>
                            </thead>

                            <tbody>
                                {this.state.data.map((obj,i)=>{
                                    return <tr key={i}>{Object.keys(obj).map((property)=>{
                                        return <td key={property}>{obj[property]}</td>

                                    })}<td><button onClick={()=>{this.editUser(obj,i)}} className="btn btn-info">Edit</button></td>
                                    <td><button onClick={()=>{this.deleteUser(i)}} className="btn btn-danger">Delete</button></td></tr>
                                })}
                            </tbody>
                            <Link to ="/">  <button type="button" className="btn btn-primary" >Back</button></Link> 
                        </table>
                        </div>
                        </div>
              </div>
            )
          }
        }
        export default Form;

1 个答案:

答案 0 :(得分:0)

删除很简单。当您遍历数据的本地状态时,如果delete axios调用成功,则需要从本地状态删除数据,

deleteUser=(i)=>{
    console.log("deleteUser called",i)
    axios.delete("http://localhost:3000/data/"+this.state.data[i].id).then(res=>{
        console.log("success");

        this.state.data.splice(i,1); //This will delete data fro local state.

    }).catch((error)=>{
        console.log("Error Occured")
    })
}

现在要进行更新,您无法直接从没有任何关系的其他组件中setState声明状态。

this.setState({objEdit:obj})

无法完成此操作,因为objEdit来自App组件。 AppForm组件之间没有任何关系。

一种方法是您可以像这样传递obj(只是一个主意)

editUser=(obj,index)=>{
    console.log(obj,index)
    this.props.history.push({
        pathname:"/",   //probablt this is for App component
        state: {objEdit : JSON.stringify(obj)}
    })
}

当然,您需要使用Form包装withRouter组件,

export default withRouter(Form)

现在在App组件中,您可以在componentDiMount中获得此数据,

componentDidMount(){
  let objEdit = JSON.parse(this.props.location.state.objEdit)

  if(objEdit){
    this.setState({objEdit})
  }
}

现在,您将在表单中获得预填充的值,您只需要处理更新按钮的功能即可。

在更新功能中,您正在手动添加id

const objEdit = {...this.state.objEdit, id: null};

但是在这种情况下,您需要检查objEdit是否有id,如果是,则需要进行update API调用。