这是可能的。我通过 Create-React-App 文件结构使用 Redux 在 React 中实现了它。
使用 stateProps/dispatchProps 模式。
您应该已经了解要使用它的动作和减速器。
这是我最初使用https://medium.com/@notrab/getting-started-with-create-react-app-redux-react-router-redux-thunk-d6a19259f71f开始的项目
我将其包括在内,因此当我使用减速器和动作等术语时,您会知道我在说什么。
在你的动作/索引文件中
import makeAction from "./makeActionCreator";
const clearMultiplePropertiesInState = "clearMultiplePropertiesInState";
export default {
constants: {
clearMultiplePropertiesInState,
},
creators: {
clearMultiplePropertiesInState: makeAction(clearMultiplePropertiesInState
}
};
在你的 reducers/{your-reducer}.js 中
import actions from '../actions';
const { constants } = actions;
const INITIAL_STATE = {
name: "Dr Hibbert",
age: "40",
height: "180cm"
};
//#region const declarations
const { clearMultiplePropertiesInState } = constants;
//#endregion
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case clearMultiplePropertiesInState: {
var fields = action.data;
var theState = {
...state
};
for(var i = 0; i < fields.length; i++) {
theState[fields[i]] = "";
}
return theState;
}
default:
if (!action.type.includes('@@')) {
console.log(`No action for: ${action.type} type`);
}
return state;
}
}
所以你要清除的三个项目是state.name、state.age和state.height
import React from "react";
import { connect } from "react-redux";
import { Form, Icon, Button, Modal } from "semantic-ui-react";
import actions from "common/actions";
const { creators } = actions;
const MyComponent = ({ stateProps, dispatchProps }) => {
return (
<React.Fragment>
<Button
disabled={disableOkButton}
onClick={() => {
dispatchProps.clearMultiplePropertiesInState(["name", "age", "height"]);
}}
primary
labelPosition='right'
icon='checkmark'
content="Create Club"
loading={stateProps.modalOkButtonLoading}
/>
</React.Fragment>
);
}
function mapStatetoProps(state) {
return {
stateProps: {
name: state.name,
age: state.age,
height: state.height
}
};
}
function mapDispatchToProps(dispatch) {
return {
dispatchProps: {
clearMultiplePropertiesInState: (fieldNames) => {
dispatch(creators.clearMultiplePropertiesInState(fieldNames));
}
}
};
}
export default connect(mapStatetoProps, mapDispatchToProps)(MyComponent);
正如我所说,您需要精通将 React 与 Redux 结合使用才能理解这一点,但这是可能的。此示例显示我同时重置 3 个值。所以成像也传递新值......
我通常有一个我使用的 changeSinglePropInState 操作(未包含在代码中),它传递了它想要更改状态的 fieldName 和 fieldValue,因为我不想为我的状态中的每个项目创建一个操作。
另外,如果你可以绕开它,这会改变状态内对象的一个属性
case addItemToWishList: {
return {
...state,
buyer: {
...state.buyer,
wishlist: action.data
}
};
}