【发布时间】:2021-08-17 20:11:55
【问题描述】:
当用户更改他们的国家/地区时,我正在尝试从表单中清除字段(从商店中清除状态),所以我想知道是否可以在一个事件下调度两个动作...... - 我的动作也是没有清除这些字段,所以不确定我哪里出错了
在 index.jsx 中
export default function Form() {
const {
apartmentNumber,
birthDay,
birthMonth,
birthYear,
buildingNumber,
countryCode
} = state;
const [formData, setFormData] = useState({
apartmentNumber,
birthDay,
birthMonth,
birthYear,
buildingNumber
});
const onInputChange = (attribute, value) => {
setFormData({
...formData,
[attribute] : value
});
};
const onCountryChange = (value) => {
dispatch(updateCountry(value));
dispatch(clearForm(formData));
};
在 reducer.js 中 --
export const initialState = {
apartmentNumber : '',
birthDay : '',
birthMonth : '',
birthYear : '',
buildingNumber : ''
};
export default (state, action) => {
const { payload, type } = action;
switch (type) {
case UPDATE_COUNTRY:
return {
...state,
countryCode : payload
};
case UPDATE_FIELDS: {
return {
apartmentNumber : initialState.apartmentNumber,
birthDay : initialState.birthDay,
birthMonth : initialState.birthMonth,
birthYear : initialState.birthYear,
buildingNumber : initialState.buildingNumber
};
}
default:
return state;
}
};
【问题讨论】:
-
查看
redux-thunk。 -
你为什么要使用 reducer 并且 state 好像它们是可以互换的?如果您使用 usestate 渲染组件,我认为您的组件在更改减速器状态时不会重新渲染。对于这种情况,我建议保留其中一个并在隔离组件中使用它或使用状态,但从减速器传递道具。
-
你在你的 Rect 组件中使用了 useReducer 吗?您可以构建 reducer 来处理动作数组,在触发通过树的状态传播之前将它们应用于状态。
标签: javascript reactjs