我正在开发JQuery应用程序。我想添加Redux存储以在添加功能时开始处理应用程序状态。如何获得多个元素来订阅发生在子状态中的调度动作?
我希望能够执行类似于connect()如何使用mapStateToProps和mapDispatchToProps连接react-redux中的多个组件的操作。示例here和here。
const CHECKBOX_CLICK = 'CHECKBOX_CLICK';
function checkboxClick(id, value) {
return {
type: CHECKBOX_CLICK,
id,
value,
}
}
const monsterCheckboxReducer = (state = [], action) => {
const {
type,
...actionData
} = action;
switch (type) {
case CHECKBOX_CLICK:
console.log(actionData);
return [...state, actionData];
default:
return state;
}
};
const appReducer = Redux.combineReducers({
monsterCheckbox: monsterCheckboxReducer,
});
const enhancers = Redux.compose(
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
const defaultState = [];
const store = Redux.createStore(
appReducer,
defaultState,
enhancers
);
const unsubscribe = store.subscribe(() => {
console.log('state changed:', store.getState())
});
$("#monsterFeaturesCheckbox :checkbox").change(function() {
store.dispatch(checkboxClick(this.id, this.checked));
//The usual JQuery way to handle events
if (this.checked) {
//Do stuff
}
});
body {
font-size: 1.3em;
background: gray;
color: bisque;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>
<fieldset id="monsterFeaturesCheckbox">
<legend>Choose some monster features</legend>
<div>
<input type="checkbox" id="scales" name="feature" value="scales" checked />
<label for="scales">Scales</label>
</div>
<div>
<input type="checkbox" id="horns" name="feature" value="horns" />
<label for="horns">Horns</label>
</div>
<div>
<input type="checkbox" id="claws" name="feature" value="claws" />
<label for="claws">Claws</label>
</div>
</fieldset>
<fieldset id="boxyCheckbox">
<legend>Choose some box features</legend>
<div>
<input type="checkbox" id="reinforced" name="feature" value="reinforced" />
<label for="reinforced">reinforced</label>
</div>
<div>
<input type="checkbox" id="locked" name="feature" value="locked" />
<label for="locked">locked</label>
</div>
</fieldset>