【问题标题】:Why redux-form wizard form can't save state?为什么 redux-form 向导表单无法保存状态?
【发布时间】:2016-09-06 07:34:43
【问题描述】:

我有一个使用redux-form的两步向导表单,但是当我返回第一页时,第一页的状态消失了,我的表单如下:

我的容器组件:

...
import Add1 from './Add1';
import Add2 from './Add2';

class Add extends Component{
    render(){
        let { add } = this.props;
        return (
            <div>
                {add.get('step') == '1' && <Add1 {...this.props}/>}
                {add.get('step') == '2' && <Add2 {...this.props}/>}
            </div>
        );
    }
}

export default Add;

我的 Add1 组件:

...
export const fields = ['username', 'password'];

class Add1 extends Component{
    toNextStep(){
        //change the step of state;
    }
    render(){
        let {fileds:{username, password}, handleSubmit} = this.props;

        return (
            <form onSubmit={handleSubmit(this.toNextStep.bind(this))}>
                <input type="text" {...username}/>
                <input type="text" {...password}/>
                <input type="submit" value="Next Step"/>
            </form>
        );
    }
}

export default reduxForm(
    {
        form: 'add',
        fields,
        destroyOnUnmount: false
    }
)(Add1);

我的 Add2 组件:

...
export const fields = ['username', 'password', 'sex'];

class Add2 extends Component{
    toPrevPage(){
        //change the step of state;
    }
    render(){
        let {fields: {sex},handleSubmit} = this.props;
        return (
            <div>
               <select {...sex}>
                    <option value="1">Male</option>
                    <option value="2">Female</option>
               </select>
               <button type="button" onClick={this.toPrevPage.bind(this)}>Prev</button>
            </div>
        );
    }
}

export default reduxForm(
{
    form: 'add',
    fields: fields,
    destroyOnUnmount: false
},
state => {
    return {
        //If I have initalValues here, the problem is arisen!!!!
        initialValues: {
            sex: 2
        }
    }
}
)(Add2);

问题是:当我在第二页有initialValues时,我点击Prev按钮,第一页的状态第一次消失(用户名和密码),我不知道如何处理这个问题,有人可以帮帮我?

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

    不需要有不同的表单名称。但是这个错字可能会导致问题。

    let {fileds:{username, password}, handleSubmit} = this.props;
         ^^^^^^
    

    【讨论】:

      【解决方案2】:

      您需要为您的表单分配不同的名称,例如 form: 'add1'form: 'add2',然后您将为每个表单分配不同的状态,这样它们就不会被覆盖

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        • 2016-12-29
        相关资源
        最近更新 更多