我正在尝试设置输入字段的状态。
我想在按键时更新特定的输入值。
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"
}
}
}
}
}
答案 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'
}
})
}))