React - POST数据到数据库后如何重新呈现组件(mongodb)

时间:2018-04-27 08:57:55

标签: mongodb reactjs post get

我正在构建将数据发送到我的数据库(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;

3 个答案:

答案 0 :(得分:0)

您可以在发布数据后重新添加组件

,添加标准函数this.forceUpdate()

答案 1 :(得分:0)

您需要在帖子回复中更新您的状态。默认情况下,当组件的状态或道具发生更改时,组件将重新呈现。

解决方案1:

axios.post('http://localhost:3001/users', newUser)
        .then(response => {
            console.log(response.data); //need to be your new "user" from server response
        //You can update your "users" state there with add new user in your state
        });

解决方案2:

axios.post('http://localhost:3001/users', newUser)
        .then(response => {
            console.log(response.data); //need to be your new "user" from server response
            //You can send your "get" request again to update your component state
            axios.get('http://localhost:3001/users')
                .then(res => {
                const users = res.data;
                this.setState({ users });
                console.log(this.state.users);
            })
        });

答案 2 :(得分:0)

只需按下阵列即可更新状态,然后重新渲染。

 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呼叫之前的状态,并仅在呼叫失败时恢复。这称为Optimistic UI

注意:您可以处理多个输入更改,例如this