【发布时间】:2020-10-30 21:09:21
【问题描述】:
我有一个连接的组件,它从 Redux 存储中获取信息并将其显示在屏幕上。但是每当我尝试发送一个动作来更新状态时,它最终都不会做任何事情:
AppSettings.js
import {
MINUTE_MS,
MINUTE_S,
} from '../constants'
import {
decrementSession,
incrementSession,
} from './timerSlice'
import React from 'react'
import { connect } from 'react-redux'
import equal from 'fast-deep-equal'
/* eslint-disable no-useless-constructor */
export class AppSettings extends React.Component {
constructor(props) {
super(props)
this.state = {
sessionLength: this.props.sessionLength,
}
}
componentDidUpdate(prevProps) {
if (!equal(this.props, prevProps)) {
this.setState((_, props) => {
return {
sessionLength: props.sessionLength,
};
})
}
}
render() {
let sessionLength = Math.floor(this.props.sessionLength / MINUTE_MS) % MINUTE_S
sessionLength = ('0' + sessionLength).slice(-2)
return (
<div>
<div>
<h3>
session
</h3>
<button
id='sessionUp'
onClick={this.props.incrementSession}
>
up
</button>
<h4>
{sessionLength}
</h4>
<button
id='sessionDown'
onClick={this.props.decrementSession}
>
down
</button>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
sessionLength: state['sessionLength'],
};
}
function mapDispatchToProps() {
return {
decrementSession,
incrementSession,
};
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(AppSettings)
timerSlice.js
import {
DEFAULT_SESSION,
MINUTE_MS,
} from '../constants'
import { createSlice } from '@reduxjs/toolkit'
export const timerSlice = createSlice({
name: 'timer',
initialState: {
sessionLength: DEFAULT_SESSION,
},
reducers: {
decrementSession(state) {
state['sessionLength'] -= MINUTE_MS
},
incrementSession(state) {
state['sessionLength'] += MINUTE_MS
},
}
})
export const {
decrementSession,
incrementSession,
} = timerSlice.actions
export default timerSlice.reducer
store.js
import { configureStore } from '@reduxjs/toolkit'
import reducer from '../features/timerSlice'
const store = configureStore({
reducer: reducer
})
export default store
在初始渲染时,组件从存储中读取就可以了,并显示适当的值。单元测试表明,组件在传递新道具时会更新呈现在屏幕上的值。我的单元测试还表明,只要按下按钮,就会调用适当的函数。我在浏览器中运行我的应用程序,它显示 Redux 商店根本没有更新。
为什么我的商店在我尝试从我的组件调度操作时没有响应?
【问题讨论】:
-
你安装了 redux-devtools(浏览器扩展)吗?您能否验证您的商店至少注册了已发送的操作?它可以方便地让您直接从开发工具 BTW 调度操作。如果您看到记录的操作,请检查操作负载(如果有)和状态差异。
-
@DrewReese 原来商店没有注册该操作已被调度。当我使用 redux-devtools 手动调度
timer/incrementSession类型的操作时,它会注册更改,但当我单击应用程序上的任何按钮时不会。在这种情况下你有什么建议?
标签: javascript reactjs redux react-redux redux-toolkit