在我的组件中,有复选框。当我单击它们时,我希望将选定的复选框保存为redux状态并更新我的组件,因此选定的复选框应显示为选中状态。这是我的组件:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {selectIngredient} from '../actions';
class Ingredient extends Component {
constructor(props) {
super(props)
this.isSelected = this.isSelected.bind(this);
this.handleCheckbox = this.handleCheckbox.bind(this);
}
handleCheckbox(e) {
const value=e.target.value;
this.props.selectIngredient(value);
}
isSelected(id) {
return (this.props.selectedIngredients.indexOf(id) > -1)
}
render() {
return (
<div className="container">
<div className="form-check checkbox">
<label className="form-check-label">
<input checked={this.isSelected(1)}
className="form-check-input"
onClick={this.handleCheckbox}
type="checkbox" value="1" />
1
</label>
</div>
<div className="form-check checkbox">
<label className="form-check-label">
<input checked={this.isSelected(2)}
className="form-check-input"
onClick={this.handleCheckbox}
type="checkbox" value="2" />
2
</label>
</div>
<div className="form-check checkbox">
<label className="form-check-label">
<input checked={this.isSelected(3)}
className="form-check-input"
onClick={this.handleCheckbox}
type="checkbox" value="3" />
3
</label>
</div>
</div>
);
}
}
function mapStateToProps(state, ownProps){
const {selectedIngredients} = state;
return {selectedIngredients}
}
export default connect(mapStateToProps,{selectIngredient})(Ingredient);
这是action / index.js
import {SELECT_INGREDIENT} from "../constants";
export function selectIngredient(selected){
const action = {
type: SELECT_INGREDIENT,
selected
}
return action;
}
这是减速器:
import {SELECT_INGREDIENT} from "../constants";
export default (state={selectedIngredients:[]}, action)=>{
let stateBefore = Object.assign({},state);
switch(action.type){
case SELECT_INGREDIENT:
const {selected} = action;
stateBefore['selectedIngredients'].push(+selected);
return stateBefore
default:
return state;
}
}
当我单击复选框时,没有任何变化,它们保持空白。组件未更新。但是redux更新了它的状态。我认为如果redux状态正在更新,那么组件及其复选框也应该更新。这是错的吗?
请帮助我弄清楚如何使这项工作。谢谢
在下面的评论中给出的答案:
在减速器中返回{...状态,selectedIngredients:[... state.selectedIngredients,action.selected]}
这是一个突变:
let stateBefore = Object.assign({},state);
...
stateBefore['selectedIngredients'].push(+selected);
您正在浅度复制状态对象,但仍会对selectedIngredients进行突变,因为它是通过引用复制的,因此您仍在修改现有的selectedIngredients对象。
检查以下问题的第一个答案https://github.com/reactjs/redux/issues/1769
使用对象传播运算符:
case SELECT_INGREDIENT:
return {
...state,
selectedIngredients: [...state.selectedIngredients, action.selected],
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句