首页 > 解决方案 > React - 如何在将数据发布到数据库后重新渲染组件(mongodb)

问题描述

我正在构建将数据发送到我的数据库(mongodb)的应用程序。在 ComponentDidMount 中,我从该数据库中获取数据,将它们保存在 this.state 中并在前端显示它们。接下来,我想从前端的表单向该数据库添加另一个数据。现在它工作正常,因为这个单个数据已添加到数据库中,但我必须刷新页面才能看到新添加的数据。

所以,我想知道如何在前端新添加的项目中动态显示到数据库。

我的第一个想法是与组件生命周期有关的东西,或者可能是在提交表单后获取数据的某些功能,但这不起作用。

有任何想法吗?

这是我的代码:

import React, { Component } from 'react';
import axios from 'axios';
import Users from './Users';

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

        this.state = {
            users: [],
            group: '',
            password: '',
            firstName: '',
            lastName: '',
            dateOfBirth: '',
            listOfUserGroups: ''
        };

        this.handleSubmit = this.handleSubmit.bind(this);
    }

    componentDidMount() {
        axios.get('http://localhost:3001/users')
          .then(res => {
            const users = res.data;
            this.setState({ users });
            console.log(this.state.users);
          })
    }

    handleGroupChange = e => {
        this.setState({ group: e.target.value });
    }

    handlePasswordChange = e => {
        this.setState({ password: e.target.value });
    }

    handleFirstNameChange = e => {
        this.setState({ firstName: e.target.value });
    }

    handleLastNameChange = e => {
        this.setState({ lastName: e.target.value });
    }

    handleDateOfBirthChange = e => {
        this.setState({ dateOfBirth: e.target.value });
    }

    handleListOfUserGroupsChange = e => {
        this.setState({ listOfUserGroups: e.target.value });
    }

    handleSubmit(e) {
        e.preventDefault();

        const newUser = {
            group: this.state.group,
            password: this.state.password,
            firstName: this.state.firstName,
            lastName: this.state.lastName,
            dateOfBirth: this.state.dateOfBirth,
            listOfUserGroups: this.state.listOfUserGroups
        };

        axios.post('http://localhost:3001/users', newUser)
            .then(response => {
                console.log('Saved');
                console.log(response.data);
                console.log(this.state.firstName);
            });
    }

    render() {
        return (
            <div>

                <div className='mainWrapper'>
                  <form className='formStyle' onSubmit={this.handleSubmit}>
                      <label>Group</label>
                      <input type="text" onChange={this.handleGroupChange} />

                      <label>Password</label>
                      <input type="text" onChange={this.handlePasswordChange} />

                      <label>First name</label>
                      <input type="text" onChange={this.handleFirstNameChange} />

                      <label>Last name</label>
                      <input type="text" onChange={this.handleLastNameChange} />

                      <label>Date of birth</label>
                      <input type="text" onChange={this.handleDateOfBirthChange} />

                      <label>List of user groups</label>
                      <input type="text" onChange={this.handleListOfUserGroupsChange} />

                      <button type="submit">Add</button>
                  </form>
                </div>

                <Users users={this.state.users} />

                <div>
                    <ul>
                        <li>{this.state.group}</li>
                        <li>{this.state.password}</li>
                        <li>{this.state.firstName}</li>
                        <li>{this.state.lastName}</li>
                        <li>{this.state.dateOfBirth}</li>
                        <li>{this.state.listOfUserGroups}</li>
                    </ul>
                </div>

            </div>
        );
    }
}

export default Main;

标签: mongodbreactjspostget

解决方案


只需推送到数组以更新状态,它将重新呈现。

 handleSubmit(e) {
    e.preventDefault();

    const newUser = {
        group: this.state.group,
        password: this.state.password,
        firstName: this.state.firstName,
        lastName: this.state.lastName,
        dateOfBirth: this.state.dateOfBirth,
        listOfUserGroups: this.state.listOfUserGroups
    };

    axios.post('http://localhost:3001/users', newUser)
        .then(response => {
            console.log('Saved');
            this.setState(prevState=>({
              users: [newUser, ...prevState.users]
            }))
            console.log(response.data);
            console.log(this.state.firstName);
        });
}

或者,如有必要,您可以推送到调用之前的状态axios并仅在调用失败时恢复。这称为乐观 UI

注意:您可以像这样处理多个输入更改


推荐阅读