我有一个Redux内存应用程序,在我的Redux状态下,我有16个卡对象数组。我想根据称为randomize
我试图对减速机中的卡片进行排序,并删除randomize
属性:
const INITIAL_STATE = {
deck: sort([{name: "Card 1"}, {...}, ...]),
...
}
但这会使我的4x4字段中的onClicks混乱。当我单击卡时,选择的卡与我单击的卡不同。 sort
算法应该不是问题:
function sort(cards) {
const deck = cards;
let currentIndex = deck.length;
let temporaryValue;
let randomIndex;
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = deck[currentIndex];
deck[currentIndex] = deck[randomIndex];
deck[randomIndex] = temporaryValue;
}
return deck;
}
我想对称为无状态组件的卡片进行排序:
import { connect } from "react-redux";
import { select_card } from "../Redux/Actions/actions";
import CardField from "./CardField";
const getRandomizedDeck = (deck, randomize) => {
if (randomize) {
return sort(deck);
// Change randomize to false somewhere
}
};
const mapStateToProps = state => ({
deck: getRandomizedDeck(state.deck, state.randomize),
backside: state.backside
});
const mapDispatchToProps = dispatch => ({
onClick: (id, name) => {
dispatch(select_card(id, name));
}
});
const RandomizedDeck = connect(
mapStateToProps,
mapDispatchToProps
)(CardField);
export default RandomizedDeck;
答案 0 :(得分:0)
我发现我的问题不是排序或调度动作,而是我的减速器在对卡片进行排序后检查错误的id
。
要回答我的问题,我发现最好添加一个名为RESET_GAME
的动作,并使该动作在减速器中对卡片进行排序,如下所示:
case RESET_GAME: {
return {
...state,
currentPlayer: 1,
deck: state.deck
.map(card => ({ ...card, selected: false, open: false }))
.sort(() => Math.random() - 0.5),
playerInfo: state.playerInfo.map(player => ({ ...player, points: 0 }))
};
}