有一個陣列看起來如下:Javascript - array.map匹配索引
[[3,0],[6,0],[2,0],[9,0] ....]
我試圖創建一個React/Redux reducer,將其中一個0的值更改爲1.我點擊一個元素並分派一個操作。 IDX是一個元件的陣列中的索引(例如,0,1,2,3)
export const toggleTile = (idx) => {
return {
type: TOGGLE_TILE,
idx
};
};
減速器下面不工作,因爲我想的那樣。我剛剛創建了條件語句的框架。如果我點擊索引爲3的圖塊(所以第四個圖塊),它會將所有元素的[n,0]更改爲[n,1]。首先,它應該只會點擊任何一個圖塊,並且它應該將[n,0]更改爲[n,1]僅用於點擊的圖塊,因此我試圖將下面的代碼中的3更改爲被映射的'i'元素的索引。
export default (state = [], action = {}) => {
switch (action.type) {
case LOAD_GRID:
return action.payload || [];
case TOGGLE_TILE:
return state.map((i) => {
if (action.idx === 3) {
return (i[1] === 0
? [i[0], parseInt(i[1], 10) + 1]
: [i[0], parseInt(i[1], 10) - 1]
);
}
return [i[0], i[1]];
});
default:
return state;
}
};
網格組件:
export default class Grid extends Component {
render() {
const mygrid = [];
this.props.inGrid.forEach((r, i) => {
mygrid.push(
<Square
key={i}
idx={i}
sqValue={r}
toggleTile={this.props.toggleTile}
/>
);
});
const { grid } = styles;
return (
<View style={grid}>
{mygrid}
</View>
);
}
}
export default class Square extends Component {
myaction() {
this.props.toggleTile(this.props.idx);
console.log(this.props.idx);
}
render() {
const { square, textStyle, squareActive } = styles;
const { sqValue } = this.props;
return (
<TouchableHighlight
style={[square, sqValue[1] && squareActive]}
onPress={this.myaction.bind(this)}
>
<View>
<Text style={textStyle}>{sqValue[0]},{sqValue[1]}</Text>
</View>
</TouchableHighlight>
);
}
}
請指教。
這是「[[3,0],[6,0],[2,0],[9,0] ... ](「我)=」{ – SoEzPz
是的,這是返回的狀態。 – Wasteland