javascript - 编辑方法未检索适当的信息 [错误] React

标签 javascript json reactjs

我使用 asp.net MVC 开发了一个基本的 API,它用作基本的用户 CRUD。 (创建、读取、更新和删除)

我已经开始使用 ReactJS 创建一个前端,它具有添加用户模式表单、编辑用户模式和删除功能。

enter image description here

GET、POST 和 DELETE 功能都可以工作,唯一的问题来自 PUT。当我单击“编辑用户”模式时,仅显示 ID。

editUserModal.js的代码如下:

const BASE_API_URL = `http://localhost:56062/api/users`;


export class EditUserModal extends Component{
    constructor(props){
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }



    componentDidMount(){
        fetch(BASE_API_URL)
        .then(response => response.json())
        .then(data => {
        this.setState({deps:data});
        });
      }

    handleSubmit(event){
        event.preventDefault();
        fetch(BASE_API_URL,{
            method:'PUT',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({

                Id:event.target.Id.value,
                firstName:event.target.firstName.value,
                lastName:event.target.lastName.value,
                Email:event.target.Email.value,
                mobileNumber:event.target.mobileNumber.value,
                dateOfBirth:event.target.dateOfBirth.value,
                lastModified:event.target.lastModified.value
            })
        })
        .then(res=> res.json())
        .then((result) =>
        {
            console.log(result);
        },
        (error) => {
            console.log('Failed')
        }
        )
    }

    render(){
        return(
            <Modal
            {...this.props}
            size="lg"
            aria-labelledby="contained-modal-title-vcenter"
            centered
          >
            <Modal.Header closeButton>
              <Modal.Title id="contained-modal-title-vcenter">
                Edit User
              </Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <div className="editFormContainer">
                  <Row>
                      <Col sm={12}>
                          <Form onSubmit={this.handleSubmit}>

                          <Form.Group controlId="Id">
                                <Form.Label>User ID</Form.Label>
                                <Form.Control name="Id" disabled defaultValue = {this.props.userid} type="text" placeholder="Id" />
                              </Form.Group>
                              <Form.Group controlId="firstName">
                                <Form.Label>First Name</Form.Label>
                                <Form.Control name="firstName" required  type="text" defaultValue = {this.props.firstname} placeholder={this.props.firstname} />
                              </Form.Group>
                              <Form.Group controlId="lastName">
                                <Form.Label>Last Name</Form.Label>
                                <Form.Control name="lastName" required type="text" defaultValue = {this.props.lastname} placeholder="Last Name"  />
                              </Form.Group>
                              <Form.Group controlId="Email">
                                <Form.Label>Email address</Form.Label>
                                <Form.Control name="Email" required type="email" defaultValue = {this.props.useremail} placeholder="Email e.g. name@example.com" />
                              </Form.Group>
                              <Form.Group controlId="mobileNumber">
                                <Form.Label>Mobile Number</Form.Label>
                                <Form.Control name="mobileNumber" required type="text" defaultValue = {this.props.mobilenumber} placeholder="Mobile e.g. 0723218223 or +447236475886" />
                              </Form.Group>
                              <Form.Group controlId="dateOfBirth">
                                <Form.Label>Date of Birth</Form.Label>
                                <Form.Control name="dateOfBirth" required type="date" defaultValue = {this.props.dateofbirth} placeholder="Date of Birth e.g. 05-02-97" />
                              </Form.Group>
                            <Form.Group>
                                <Button variant="primary" type="submit">Edit User</Button>
                            </Form.Group>

                          </Form>
                      </Col>
                  </Row>
              </div>
            </Modal.Body>
            <Modal.Footer>
              <Button variant="danger" onClick={this.props.onHide}>Close</Button>
            </Modal.Footer>
          </Modal>
        )
    }
}

包含表(User.js)的代码如下:

export class User extends Component {

    constructor(props){
        super(props);
        this.state = {users:[], addModalShow : false, editModalShow: false}

    }

    componentDidMount(){
        this.refreshList();

    }

    refreshList(){
      fetch(BASE_API_URL)
      .then(response=> response.json())
      .then(data => {
          this.setState({users:data})
      })
    }

    componentDidUpdate(){
      this.refreshList();

  }

    deleteUser(userid)
    {
      if(window.confirm('Are you sure?'))
      {
          fetch(`http://localhost:56062/api/users/`+userid,{
              method:'DELETE',
              header:{'Accept':'application/json',
              'Content-Type':'application/json'
          }
          })
      }
    }
render(){

    const {users, userid, firstname, lastname, useremail, mobilenumber, dateofbirth, lastmodified} = this.state;
    let addModalClose =() => this.setState({addModalShow:false});
    let editModalClose =() => this.setState({editModalShow:false});

    return(
        <div>
            <ButtonToolbar>
              <Button variant='outline-dark' onClick={()=> this.setState({addModalShow:true})}>
                  Add User
              </Button>
                <AddUserModal show={this.state.addModalShow} onHide={addModalClose} />
              </ButtonToolbar>

        <Table responsive striped hover size="sm" variant="dark" className="mt-4">
   <thead>
     <tr>
       <th>Id</th>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Email</th>
       <th>Mobile Number</th>
       <th>Date of Birth</th>
       <th>Last Modified</th>
       <th>Edit</th>
       <th>Delete</th>
     </tr>
   </thead>
   <tbody>
        {users.map(user=> 
          <tr key = {user.Id}>
            <td>{user.Id}</td>
            <td>{user.firstName}</td>
            <td>{user.lastName}</td>
            <td>{user.Email}</td>
            <td>{user.mobileNumber}</td>
            <td>{user.dateOfBirth}</td>
            <td>{user.lastModified}</td>
            <td>
              <ButtonToolbar>
              <Button className="mr-2" variant="outline-light" onClick={()=> this.setState({editModalShow:true, userid:user.Id, mobilenumber:user.mobileNumber, dateofbirth:user.dateOfBirth, lastmodified:user.lastModified})}>
              Edit User
              </Button>
                <EditUserModal 
                show = {this.state.editModalShow} 
                onHide = {editModalClose} 
                userid = {userid} 
                firstname = {user.firstName}
                lastname = {user.lastName}
                useremail = {user.Email}
                mobilenumber = {user.mobileNumber}
                dateofbirth = {user.dateOfBirth}
                lastmodified = {user.lastModified} />
              </ButtonToolbar>
              </td>
              <td>
              <Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button>
              </td>

          </tr>
          )}
   </tbody>
 </Table>

 </div>
    )
}

}

所以我认为问题出在 User.js 中的这部分代码

我正在查看的指南的代码似乎在这样编写时加载了所有适当的字段,

<EditUserModal 
show = {this.state.editModalShow} 
onHide = {editModalClose} 
userid = {userid} 
firstname = {firstname}
lastname = {lastname}
useremail = {useremail}
mobilenumber = {mobilenumber }
dateofbirth = {dateofbirth }
lastmodified = {lastmodified } />

当代码像这样编写时,由于某种原因,只有 Id 和手机号码会加载到“编辑用户”模式中。

enter image description here

而当我有这样的代码时,它会显示该列的正确 ID,然后显示最后插入的列的所有信息,如下所示。

<EditUserModal 
show = {this.state.editModalShow} 
onHide = {editModalClose} 
userid = {userid} 
firstname = {user.firstName}
lastname = {user.lastName}
useremail = {user.Email}
mobilenumber = {user.mobileNumber}
dateofbirth = {user.dateOfBirth}
lastmodified = {user.lastModified} />

enter image description here

上图应显示用户 13,但显示的是最后一次输入(即用户 17)的其余信息。

enter image description here

发生这种情况有什么具体原因吗?也许我以一种不好的方式设置状态?

========================更新====================== ===========

我现在已经在组件内设置了一个关键 Prop ,但同样的事情发生了,当加载编辑模式时,只有 ID 和手机号码出现在文本框中。

<EditUserModal 
              show = {this.state.editModalShow} 
              key = {userid}
              onHide = {editModalClose} 
              userid = {userid} 
              firstname = {firstname}
              lastname = {lastname}
              useremail = {useremail}
              mobilenumber = {mobilenumber}
              dateofbirth = {dateofbirth}
              lastmodified = {lastmodified} />

最佳答案

EditUserModal 组件上设置一个名为 key 的属性,并将其设置为 userId 值。

您可以阅读有关此的更多信息 here

关于javascript - 编辑方法未检索适当的信息 [错误] React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59888078/

相关文章:

java - Jackson 序列化和反序列化日期时间从/到 WCF 日期时间

javascript - 平滑向上滑动动画(React Native Animation)

json - 斯卡拉 : How to do GroupBy sum for String values?

javascript - Promise 的递归

javascript - 如何释放和垃圾收集 WebGL 上下文?

javascript - Angular JS Controller 多次注入(inject)

android - Json 数据已发布到服务器但始终获取 "com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of"

reactjs - 如何使用 Material ui 处理快速拨号操作?

javascript - 尽管异步计算,Redux 最小状态?

javascript - 如何将 url 放入 img 标签 (html) 中?