ReactJS HREF Causes State Loss

回眸只為那壹抹淺笑 提交于 2021-02-11 14:37:52

问题


I have a parent component called EnrollForm with a BrowserRouter that routes to different sub-components which are the pages of my overall EnrollForm.

Each time a sub-component page is filled out and next btn is clicked, all form fields are saved to sub-component state obj, then that state is passed to the parent EnrollForm state. This flow is working correctly.. however when I added the line of code to href to the next sub-component, the parent EnrollForm state is deleted and so is BioForm's state.

Any help would be so greatly appreciated, It's probably simple but I've been looking at it for so long...

EnrollForm Component:

class EnrollForm extends Component {
    state = {

    }

    setParentFormState = (newStateObj, fromComponent) => {
        this.setState({...this.state, ...newStateObj}, () => {
            console.log('Updated EnrollForm component state from ' + fromComponent);
            console.log(this.state);
        });
    }

    render() {
        return (
            <Router>
                <div className='workflow'>
                    <Route path='/enrollment-form/bio' render={(routeProps)=>(<BioForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/citizenship' render={(routeProps)=>(<CitizenshipForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/identity' render={(routeProps)=>(<IdentityForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/attributes' render={(routeProps)=>(<AttributesForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/address' render={(routeProps)=>(<AddressForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/eligibility' render={(routeProps)=>(<EligibilityForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/documents' render={(routeProps)=>(<DocumentsForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/location' render={(routeProps)=>(<LocationForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/appointment' render={(routeProps)=>(<ApptTimeForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                    <Route path='/enrollment-form/status' render={(routeProps)=>(<StatusForm {...routeProps} setParentFormState={this.setParentFormState}/>)}/>
                </div>
            </Router>
        );
    }
}

export default EnrollForm;

BioForm Component:

class BioForm extends Component {
    state = {
        first_name: null,
        middle_name: null,
        last_name: null,
        u_suffix: null,
        u_gender: null,
        u_dob: null,
        u_lang: null,
        u_email: null,
        u_country_code_1: null,
        u_country_code_2: null,
        u_phone_1: null,
        u_phone_2: null,
        u_contact_method: null

    }

    nextButtonClicked = event => {
        let form = document.getElementById('applicant-form');
        let formDataJsObj = FormFunctions.getJsObjFromFormData(form);
        let keyToDelete = 'u_email[verify]';
        //This field is removed from the form data object because it is not sent in the POST request
        FormFunctions.removeKeyFromFormObj(formDataJsObj, keyToDelete);
        console.log(formDataJsObj);
        this.setState(formDataJsObj, () => {
            this.props.setParentFormState(this.state, this.constructor.name);
            console.log('BioForm data submitted and parent state updated.. changing pages.');
            window.location.href = '/enrollment-form/citizenship';
        });



    }
    render(){//markup}
}

回答1:


This cause a page reload, which reset your all you states (Redux included) and render everything again:

window.location.href = '/enrollment-form/citizenship';

Replace it by:

this.props.history.push('/enrollment-form/citizenship')

Note that you might need to wrap your component with withRouter like this:

export default withRouter(EnrollForm);

With the import:

import { withRouter } from "react-router";

Hope it helps. Happy coding!




回答2:


Never use href with react, instead use for declarative change route, or wrap component in withRouter and use history.push for imperative change



来源:https://stackoverflow.com/questions/59417162/reactjs-href-causes-state-loss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!