简体   繁体   中英

How to clear a field after submitting a form and display the form values after the page reloads

CODE:

import React, { Component } from 'react';

import classes from './Form.css';

class Form extends Component {

    state = {
        firstName: '',
        phoneNo: '',
        showForm: false
    }

    displayFormHandler = (e) => {
        e.preventDefault();
        const updatedName = e.target.value;
        this.setState({
            firstName: updatedName,
        });

    }

    displayPhoneNoHandler = (e) => {
        e.preventDefault();
        const updatedPhoneNo = e.target.value;
        this.setState({ phoneNo: updatedPhoneNo });
    }

    handleFormSubmit = (e) => {
        e.preventDefault();
        this.setState({
            showForm: true
        });



    }
    render() {
        return (
            <div className={classes.Form}>
                <form onSubmit={this.handleFormSubmit}>
                    <label>Name:</label>
                    <input type="text" 
                        className={classes.inputArea}
                        name="firstName"
                        placeholder="Name"
                        onChange={this.displayFormHandler}
                        value={this.state.firstName} />
                    <label>PhoneNo:</label>
                    <input type="text"
                        className={classes.inputArea}
                        placeholder="PhoneNo"
                        name="phoneNo"
                        onChange={this.displayPhoneNoHandler}
                        value={this.state.phoneNo} />
                    <button type="submit" className={classes.Button}
                        clicked={this.handleFormSubmit}  >Submit</button>
                    <div className={classes.UserInfo}>
                        {this.state.showForm && <p>UserName: {this.state.firstName}</p>}
                        {this.state.showForm && <p>UserName: {this.state.phoneNo}</p>}


                    </div>

                </form>
            </div>

        );
    }
}

export default Form;

The code is mentioned above.

I created a form in React.JS. It echoes back the data from the form response; however, the data suddenly disappears after refreshing the page. I would like to find a suitable method that would allow me to store the user's response to the form and display it (even after the page has been refreshed).

即使在用户重新加载页面后也要显示表单数据,您可以使用浏览器的本地存储,并且在每个会话开始时只需读取存储的数据即可。

If you want to display form data after page reload you need to store them somewhere best place would use browser local storage API. To clear form data after submit is easy just add your two input state values to setState method that you already have in your submit method.

Firstly we will try to get data from localStorage in constructor of the component class. If localStorage is not empty we set its value as default component state. Here is a code example.

constructor() {
   const data = JSON.parse(localStorage.getItem('formData')); // get data from localStorage and parse it.
   if (data !== null) { // Check if data even exists
     this.state = { 
       firstName: data.firstName,
       phoneNo: data.phoneNo,
       showForm: false
     }; // set default React state.
   }
}

Secondly set the data after form submit. Here is another code example.

handleFormSubmit = (e) => {
        e.preventDefault();
        const {firstName, phoneNo} = this.state;
        localStorage.setItem('formData', JSON.stringify({ firstName, phoneNo })); // parse the data and save it.
        this.setState({
            firstName: '',
            phoneNo: '',
            showForm: true
        }); // Clear the form data
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM