我有8个<TouchableWithoutFeedback>
元素的网格形式。它们不使用地图动态渲染。
this.props.selectCell(&#39;雨&#39;)}&GT;
<TouchableWithoutFeedback onPress={()=>this.props.selectCell('rain')}>
<Row style={[styles.orangish,styles.cell]}>
<Image source={Rain} />
</Row>
</TouchableWithoutFeedback>
想法是选择一个onPress。
行动
export const selectCell = (cellId) => {
console.log(cellId);
return {
type: 'select_cell',
payload: cellId
};
}
减速
export default (state= {}, action) => {
switch(action.type) {
case 'select_cell': {
//trying to figure out what to do here
}
};
1)如何在reducer中切换选择?
2)如何基于状态渲染新图像?
答案 0 :(得分:1)
在reducer状态下有一个selectedCellId属性并将其设置如下:
export default (state= {}, action) => {
switch(action.type) {
case 'select_cell': {
return {
...state,
selectedCellId: action.payload
};
}
};
另一种方法是使用一个包含selected = false的8个单元格的数组。
const defaultState = {
cells: [
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false }
]
};
然后在减速器中,
export default (state= defaultState, action) => {
switch(action.type) {
case 'select_cell': {
let { cells } = state;
cells = cells.slice();
cells[action.payload] = { selected: true };
return {
...state,
cells
};
}
};
如果您已命名单元格,则将单元格集合设为对象图而不是数组。