reactjs - Why is my state not updating after useDispatch
问题描述
Ive got a pretty straightforward set-up. That seems to be alright at least on my unexperienced first glance, however upon trying to dispatch an action to toggle the state, it does not seem to do anything and I can't figure out why.
this is how my store is configured:
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
})
(... then it's obviously passed via <Provider>
)
And later down the line in my component:
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);
Now my props seems to be mapped correctly (as do seemingly my actions (though I'm new to redux), however my actions don't seem to affect my state.
I've simplified the example for sake of quesiton, but you can see obviously I've clicked the button and the state is not affected
解决方案
your problem lies in what you are dispatching.
SHORT: you don't need the useDispatch
just do onClick={props.actionToggleQuizChoices}
LONG: your
const mapDispatchToProps = { actionToggleQuizChoices }
will be translated to something like
const mapDispatchToProps = (dispatch) => ({ actionToggleQuizChoices: (...args) => dispatch(actionToggleQuizChoices(....args)) })
then inside of your component what you are actually doing is
dispatch(((...args) => dispatch(actionToggleQuizChoices()))(props.actionToggleQuizChoices))
as you can see you are dispatching a function. Functions are only interpreted either by a custom middleware or if you are using redux-thunk.
推荐阅读
- rest - AWS ALB 后面的微服务(ish)设置中的健康检查路由组织
- typescript - TypeScript 中的“复合类型”
- sql-server - 如何将多月数据放入多列
- git - 使用 Visual Studio 代码在 Visual Studio Team Server(或 gitlab)上创建远程 git 存储库
- c++ - 在排序的文本文件中实现二进制搜索?
- angularjs - 使用 ng-options 和 'as' 设置标签('track by' 替代方案)
- python - 从 Sage 中提取单一解决方案
- javascript - React 中状态更新时动态更改获取请求 url
- events - Google 表格 onEdit 事件不起作用
- android - google sheet自定义菜单功能在android上的google sheet中不可见