我在将redux存储重置为初始状态时遇到问题



我有一个应用程序(智力竞赛游戏(,用户可以点击按钮"新游戏",新游戏就会开始。当用户点击它时,我想重置我所有的redux存储。我有一个根还原器,它结合了所有的应用程序还原器。我想在点击按钮后将它们重置为初始状态。我看到Dan Abramov回答(https://stackoverflow.com/a/35641992/11580012)做了同样的事,但什么也没发生。我的意思是初始状态没有建立。

下面是一些代码:

组件类别

class GameMenu extends Component {
constructor(props) {
super(props);
this.state = {
modalIsOpen: false,
modalMessage: '',
modalType: undefined // 0 for new game, 1 for end game
};
this.openModal = this.openModal.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
openModal (e) {
this.setState({ modalIsOpen: true });
}
handleSubmit () {
this.setState({ modalIsOpen: false });
if(this.state.modalType === 0) {
this.props.startNewGame();
this.props.history.push('/');
} else {
this.props.endGame();
}
}
handleCancel () {
this.setState({ modalIsOpen: false });
}
render() {
return (
<div className="menu">
<button onClick={this.openModal} id="newGameButton">New Game</button>
<button>Leader Board</button>
<button onClick={this.openModal} id="endGameButton">End Game</button>
<Modal
isOpen={this.state.modalIsOpen}
onCancel={this.handleCancel}
onSubmit={this.handleSubmit}
>
<p>{this.state.modalMessage}</p>
</Modal>
</div>
)
}
}
const mapStateToProps = state => {
return {
players: state.players,
answeredQuestionsArray: state.questions.answeredQuestionsArray,
topics: state.questions.topics,
}
};
const mapDispatchToProps = {
startNewGame,
endGame
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(GameMenu);

根部减压器:

import { questionsReducer } from "./questions/reducers";
import { playersReducer } from "./players/reducers";
import {START_NEW_GAME} from "./actions";
import {END_GAME} from "./actions";
const appReducer = combineReducers({
questions: questionsReducer,
players: playersReducer
});
const rootReducer = (state, action) => {
if (action.type === START_NEW_GAME) {
state = undefined;
}
return appReducer(state, action);
};
export default rootReducer;
const initialState = {
answeredQuestionsArray: [],
topics: []
};
export const questionsReducer = (state = initialState, action) => {
switch (action.type) {
case CHANGE_ANSWERED_QUESTIONS_ARRAY:
return {
...state,
answeredQuestionsArray: action.payload
};
case LOAD_TOPICS:
return {
...state,
topics: action.payload
};
}
return state;
};
export const startNewGame = () => ({
type: START_NEW_GAME
});

this.props.history.push('/)之后,状态没有变为初始状态。

当您将mapDispatchToProps连接到组件时,您必须在内部调用dispatch,否则您的操作将不会被调度。例如:

const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
startNewGame: () => dispatch({ type: START_NEW_GAME })
}

使用Redux DevTools(chrome扩展(来调试这类问题很方便。

问题有所不同。我在reductor中写了不正确的逻辑。复位方式正确。谢谢你的帮助!

最新更新