【发布时间】:2021-05-06 19:33:38
【问题描述】:
我有以下带有 TypeScript 的 React 组件:
import React from 'react';
import {connect, ConnectedProps} from 'react-redux';
import logo from './assets/logo.png';
// import { Counter } from './features/counter/Counter';
import './App.css';
import {IApplicationState} from './features/application/reducers';
const mapStateToProps = (application: IApplicationState) => {
const applicationComposite = application.applicationComposite;
return {applicationComposite};
}
const connector = connect(mapStateToProps);
type PropsFromRedux = ConnectedProps<typeof connector>
interface Props extends PropsFromRedux {};
class App extends React.Component<Props> {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<span>
<span>Attractora </span>
{this.props.applicationComposite && <span>{this.props.applicationComposite.content}</span>}
</span>
</header>
</div>
);
}
}
export default connector(App);
问题是我将applicationComposite 变成undefined,即使reducer 的初始状态有一个值。
我调试了代码,发现mapStateToProps(application: IApplicationState)在application.application.applicationComposite中接收到了applicationComposite的值,但是当我尝试分配applicationComposite = application.application.applicationComposite时,却出现了这个错误:
Property 'application' does not exist on type 'IApplicationState'.
我关注了this tutorial,但我找不到我做错了什么。
编辑
这是我的根减速器:
import {combineReducers} from 'redux';
import application from '../features/application/reducers';
const rootReducer = combineReducers({
application,
});
export default rootReducer;
这是我的应用程序缩减器:
import { Dictionary } from '@reduxjs/toolkit';
import { ActionInterface } from '../generals';
import {
FETCH_APPLICATION_COMPOSITE_SUCCESS,
SET_CURRENT_APPLICATION_COMPONENT
} from './actions';
export interface IApplicationState {
applicationComposite: any,
currentApplicationComponent: string | null,
}
const INIT_STATE = {
applicationComposite: {content: 'test_content'},
currentApplicationComponent: null
}
export default (state=INIT_STATE, action: ActionInterface) => {
switch(action.type) {
case FETCH_APPLICATION_COMPOSITE_SUCCESS: {
return {
...state,
//@ts-ignore: Object is possibly 'undefined'
applicationComposite: action.payload.applicationComposite
}
}
case SET_CURRENT_APPLICATION_COMPONENT: {
return {
...state,
//@ts-ignore: Object is possibly 'undefined'
currentApplicationComponent: action.payload.applicationComponent
}
}
default: {
return state;
}
}
}
【问题讨论】:
-
你能展示一下 root 和 application reducer 的样子吗?很难概念化,因为您为状态对象的两个不同级别使用了相同的名称。
-
@lawrence-witt 我不知道我在哪里为两个不同的对象使用了相同的名称,但我将您请求的代码添加到了问题的正文中。感谢您抽出宝贵时间
-
你在 MSTP 中调用你的根状态
application,但是你有一个application直接在它上面。像application.application这样的路径很难推理。正如其他人刚刚回答的那样,您的根状态使用了不正确的界面。