[英]How can I use a static model with a form reducer in React?
主要问题是开发人员可以将他们想要的任何内容添加到标准形式的缩减器 state,而不是 static。这导致 state 更难以在不同的开发人员之间理解,并且基本上是隐藏的 model。
我最初创建了一个key/value JS object来表示表单的数据model。 然后我意识到只能通过 state 属性将它发送到 reducer,而 reducer 返回一个包含任何内容的新 state。 没有安全措施可以阻止开发人员返回 {null} 或其他疯狂的事情。
如果开发人员试图将 state 变量添加到 model 中未定义和初始化的减速器,我希望减速器失败并显示控制台警告。我觉得类当然有可能,但函数和挂钩我不确定.
export const FormModel = {
submit: false,
}
export default function FormReducer(state = FormModel, action) {
switch (action.type) {
case 'submit':
return { ...state, submit: action.payload}
default:
return state
}
}
const Form = ({}) => {
return (
<form>{/*TODO*/}</form>
)
}
export default Form
Form.propTypes = {
//TODO
}
奖励积分:集成 ajax 的最佳方式。
在这里,我想谈谈可能与您正在寻找的东西相似的一件事。
我使用与 typescript 和 eslint 的反应创建了我的应用程序。 首先,我定义了一个名为 IProfileState 的IProfileState
,然后我扩展到initialState
。
像这样:
interface IProfileState {
name: string
age: number
}
interface IState {
profile: IProfileState
}
const initialState: IState = {
profile: {
name: '',
age: 2
}
};
我将IProfileState
接口传递给PayloadAction
,它是 redux 动作的类型,就像这样。
export const uiSlice = createSlice({
name: 'ui',
initialState,
reducers: {
setUserProfile: (state, action: PayloadAction<IProfileState>) => {
state.profile = action.payload;
}
}
});
当我试图输入错误的东西或者我没有先在IProfileState
上定义它时。
我会收到这样的错误:
TS2345: Argument of type '{ name: string; age: number; gender: string; }' is not assignable to parameter of type 'IProfileState'.
Object literal may only specify known properties, and 'gender' does not exist in type 'IProfileState'.
12 | name: 'doe',
13 | age: 10,
> 14 | gender: 'male'
| ^^^^^^^^^^
15 | }));
16 | };
也许你也可以实现这个。 完整文档在这里https://react-redux.js.org/using-react-redux/usage-with-TypeScript
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.