【问题标题】:ReactJS HREF Causes State LossReactJS HREF 导致状态丢失
【发布时间】:2020-04-12 11:45:34
【问题描述】:

我有一个名为 EnrollForm 的父组件,它带有一个 BrowserRouter,它路由到不同的子组件,这些子组件是我的整个 EnrollForm 的页面。

每次填写一个子组件页面并点击next btn时,所有表单字段都会保存到子组件状态obj,然后将该状态传递给父EnrollForm状态。此流程工作正常。但是当我将代码行添加到 href 到下一个子组件时,父 EnrollForm 状态被删除,BioForm 的状态也是如此。

任何帮助将不胜感激,这可能很简单,但我已经研究了很长时间......

注册表单组件:

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 组件:

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}
}

【问题讨论】:

    标签: javascript reactjs react-router react-state-management react-state


    【解决方案1】:

    这会导致页面重新加载,这会重置您的所有状态(包括 Redux)并再次呈现所有内容:

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

    替换为:

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

    请注意,您可能需要像这样用 withRouter 包装您的组件:

    export default withRouter(EnrollForm);
    

    导入:

    import { withRouter } from "react-router";
    

    希望对您有所帮助。编码愉快!

    【讨论】:

    • 非常感谢先生的回答,这对我来说很完美。看来我需要了解更多关于 React 的事情!我不确定为什么会这样,但确实如此。我还尝试将 与 to 和 onClick 事件一起使用,但页面只会在事件处理程序运行之前重定向!我也必须弄清楚这一点。
    • 这可能是因为你做了 onClick={yourFunc} 而不是 onClick={()=>yourFunc}
    【解决方案2】:

    切勿将 href 与 react 一起使用,而是用于声明式更改路由,或将组件包装在 withRouter 中并使用 history.push 进行命令式更改

    【讨论】:

    • 我尝试使用带有 的声明式路由,但页面只是在事件处理程序触发之前重定向。谢谢(你的)信息!它现在正在使用 history.push。
    猜你喜欢
    • 2021-07-28
    • 2018-11-09
    • 1970-01-01
    • 2021-09-20
    • 2021-01-18
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多