通过setState

时间:2019-11-28 17:07:59

标签: reactjs typescript setstate

我正在尝试设置输入字段的状态。

我想在按键时更新特定的输入值。

setState状态看起来不错,但是渲染部分的贴图功能出现错误。 (this.state.form[this.state.mode].form.map

我不明白为什么它会在地图上破裂。

export type IMode = "login" | "forgot";
export interface IInput {
    value: string;
    error: string;
    id: string;
    name: string;
    placeholder: string;
    type: "text" | "password";
}
export interface IState {
    isRequestPending: boolean;
    backendError: string;
    mode: IMode;
    form: {
        [key in IMode]: {
            name: string;
            method: string;
            action: string;
            fields: IInput[];
        };
    };
}

in constructor 
       this.state = {
            isRequestPending: false,
            backendError: "",
            mode: "login",
            form: {
                login: {
                    name: "Login",
                    method: "",
                    action: "",
                    fields: [
                        {
                            value: "",
                            error: "",
                            id: "test",
                            placeholder: "Login",
                            type: "text",
                            name: "login"
                        }
                    ]
                },
                .... and so on

            }
        };
    private handleFormInput = (e, input: IInput, index) => {

        this.setState((prevState) => ({
            ...prevState,
            backendError: "",
            form: {
                ...prevState.form,
                [this.state.mode]: {
                    ...prevState.form[this.state.mode],
                       fields: {
                            ...prevState.form[this.state.mode].fields,
                           [index]: {
                                ...prevState.form[this.state.mode].fields[index],
                                value: "it Works, but map crash"
                           }
                       }
                }
            }
}

1 个答案:

答案 0 :(得分:1)

您正在将fields转换为不包含object方法的map。像这样更新您的状态

this.setState(prev =>({
   /*...*/
   fields : prev.form[this.state.mode].fields.map((field, i) =>{
       if(i !== index) return field
       return {
           ...field,
           value : 'foo'
       }
   })
}))