我有一个非常简单的设置。至少从我没有经验的第一眼看来,这似乎还不错,但是在尝试分派动作来切换状态时,它似乎无能为力,我也不知道为什么。
这是我的商店的配置方式:
import { createAction } from '@reduxjs/toolkit';
import { createReducer, configureStore } from '@reduxjs/toolkit';
// action
export const TOGGLE_QUIZ_MENU_CHOICE = 'TOGGLE_QUIZ_MENU_CHOICE';
export const actionToggleQuizChoices = createAction(TOGGLE_QUIZ_MENU_CHOICE);
// store and reducer
type StoreState = {
isMultipleChoice: boolean;
}
const initalState = {
isMultipleChoice: false,
}
const reducer = createReducer(initialState, {
[actionToggleQuizChoices.type]: (state) => ({
...state,
isMultipleChoice: !state.isMultipleChoice
})
}
const store = configureStore({
reducer
})
(...然后显然通过<Provider>
传递了)
然后在我的组件中一行:
import React from 'react';
import { connect, useDispatch } from 'react-redux';
import { actionToggleQuizChoices } from '../../../store/actions';
type Props = {
isMultipleChoice: boolean;
}
const QuizMenu: React.FC<Props> = (props: Props) => {
const dispatch = useDispatch()
console.log(props);
return (
<button type='button' onClick={() => dispatch(props.actionToggleQuizChoices)} />
)
}
const mapStateToProps = (state: StoreState): StoreState => ({
isMultipleChoice: state.isMultipleChoice
})
const mapDispatchToProps = { actionToggleQuizChoices }
export default connect(
mapStateToProps,
mapDispatchToProps
)(QuizMenu);
现在我的道具似乎已正确映射(貌似我的行为(尽管我是redux的新手),但是我的行为似乎并不影响我的状态。
为了方便起见,我已简化了示例,但您可以明显看出我单击了按钮,并且状态未受影响
答案 0 :(得分:3)
您的问题在于您要调度的东西。
简短:您不需要useDispatch
,只需onClick={props.actionToggleQuizChoices}
长: 您的
const mapDispatchToProps = { actionToggleQuizChoices }
将被翻译为类似
const mapDispatchToProps = (dispatch) => ({ actionToggleQuizChoices: (...args) => dispatch(actionToggleQuizChoices(....args)) })
然后在组件内部实际执行的操作是
dispatch(((...args) => dispatch(actionToggleQuizChoices()))(props.actionToggleQuizChoices))
如您所见,您正在分派一个函数。函数只能由自定义中间件或使用redux-thunk解释。