我正在尝试将目录组件移动到redux中,但是一直出现此错误。该类型基本上是一个对象数组。如果我将类型从“ Section”更改为any,则mapStateToProps中的section属性会抱怨“此调用没有重载”。
Property 'sections' does not exist on type '({ title: string; imageURL: string; id: number; linkURL: string; size?: undefined; } | { title: string; imageURL: string; size: string; id: number; linkURL: string; })[]'
Directory.tsx
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { selectDirectorySections, Section } from '../../redux/directory/directorySelectors';
import MenuItem, { IMenuItem } from '../menuItem/MenuItem';
import './Directory.scss';
interface IMenuItems extends IMenuItem {
id:number
};
const Directory = ({ sections }:Section) => {
return (
<div className='directory-menu'>
{sections.map(({ id, ...otherSectionProps }:IMenuItems) => (
<MenuItem key={id} {...otherSectionProps} />
))}
</div>
);
};
const mapStateToProps = createStructuredSelector({
sections: selectDirectorySections
});
export default connect(mapStateToProps)(Directory);
directorySelectors.ts
import { RootState } from '../rootReducer';
import { createSelector } from 'reselect';
const selectDirectory = (state:RootState) => state.directory;
export const selectDirectorySections = createSelector(
[selectDirectory],
directory => directory.sections
);
export type Section = ReturnType<typeof selectDirectorySections>;
directoryReducer.js
const INITIAL_STATE = {
sections: [
{
title: 'hats',
imageURL: 'https://i.ibb.co/cvpntL1/hats.png',
id: 1,
linkURL: 'hats'
}...
]
};
const directoryReducer = (state=INITIAL_STATE, action) => {
switch(action.type) {
default:
return state;
};
};
export default directoryReducer;
答案 0 :(得分:1)
在此代码中:
const Directory = ({ sections }:Section) => {
return (
<div className='directory-menu'>
{sections.map(({ id, ...otherSectionProps }:IMenuItems) => (
<MenuItem key={id} {...otherSectionProps} />
))}
</div>
);
};
您正试图从类型sections
的对象中解构属性Section
。 Section
定义为:
export const selectDirectorySections = createSelector(
[selectDirectory],
directory => directory.sections
);
export type Section = ReturnType<typeof selectDirectorySections>;
因此它具有directory.sections
的类型。从名称directory.sections
,到错误消息,这就是一个数组:
Property 'sections' does not exist on type '({ title: string; imageURL: string; id: number; linkURL: string; size?: undefined; } | { title: string; imageURL: string; size: string; id: number; linkURL: string; })[]' −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^
数组没有sections
属性(除非您添加一个属性,通常这不是一个好主意)。
您需要修改定义Section
的方式,或使用它更改代码以将其用作数组(例如,通过循环等)。