gpt4 book ai didi

reactjs - react typescript : Object is of type 'unknown' . TS2571

转载 作者:行者123 更新时间:2023-12-05 07:09:10 27 4
gpt4 key购买 nike

我正在为我的项目使用 React-TypeScript。对于状态管理,我使用 React-redux,对于函数处理,我使用 redux-saga。为了粘合 redux 存储和函数,我使用了 React 的新钩子(Hook) useSelectoruseDispatch。我成功地提取了数据并能够在控制台中显示它。 My data looks like this .根据 useSelector 文档,我可以在不传递给状态的情况下呈现 useSelector。当我映射 useSelector 的变量时,我收到 TypeScript 错误:Object is of type 'unknown'。附言。我也是 TypeScript 的新手。

这是我的 React 功能组件

import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import ErrorBoundary from 'components/errorBoundary';
import { useDispatch, useSelector } from 'react-redux';
import { IPropertiesList } from '../../state/properties/types';
import { fetchProperties } from '../../state/properties/actions';
import { IIssueListItem } from '../../state/issues/types'
import { fetchIssuesList } from '../../state/issues/actions'
import list from '../issues/list';


export interface ITestNewListProps {
className?: string;
}

const Test = ({ className }: ITestNewListProps) => {
const dispatch = useDispatch();
const properties = useSelector<IPropertiesList | undefined>(
(state: any) => state.properties.list.data
);
const issues = useSelector<IIssueListItem | undefined>(
(state: any) => state.issues.list.data
)

useEffect(() => {
// fetch the properties data from the api if we don't already have it
!properties && dispatch(fetchProperties({}));

}, [dispatch, properties]);

useEffect(() => {
!issues && dispatch(fetchIssuesList())
}, [dispatch, issues]);

console.log(`properties`, properties); //I can able to see the data
console.log(`issues`, issues);


return (
<ErrorBoundary id="TestNewListErrorBoundary">
<div className={`${className}`}>
{
properties.map(list => { // IN HERE I AM GETTING ERROR
return <div>{list.name}</div>
})
}
</div>
</ErrorBoundary>
);
};

Test.displayName = `Test`;

export default styled(Test)`
`;

最佳答案

您可能没有为您的 useSelector Hook 使用正确的类型。通常,如果您在回调函数中提供根状态的类型就足够了。

我不确定您如何为根状态命名接口(interface),但假设它被称为 RootState

const issues = useSelector(
(state: RootState) => state.issues.list.data
);

对于这种情况,不需要提供通用类型参数,因为 TypeScript 应该能够根据 RootState< 推断出 state.issues.list.data 的类型 接口(interface)/类型别名,但如果你确实想提供通用类型,

const issues = useSelector<RootState, IPropertiesList | undefined>(
(state: RootState) => state.issues.list.data
);

请注意,useSelector Hook 的泛型类型要求您输入默认的根状态类型以及选定的状态类型。

关于reactjs - react typescript : Object is of type 'unknown' . TS2571,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61671852/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com