[英]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.