我有一个react组件,并且在那个react组件中,我正在使用blueprint.js Tree fucntion根据服务器返回的json对象渲染树。我遇到了我要修复的类型问题,但是我不确定它来自哪里...这是错误:
Type 'ITreeNode<{}>[] | undefined' is not assignable to type 'ITreeNode<{}>[]'.
Type 'undefined' is not assignable to type 'ITreeNode<{}>[]'.ts(2322)
HelpTree.tsx(11, 5): The expected type comes from property 'nodes' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<HelpTree> & Readonly<State> & Readonly<{ children?: ReactNode; }>'
我不确定为什么会收到此错误或如何解决该错误。
这是源代码。我正在使用bluepring中的Tree,并且在动态构建ITreeNode之后对其进行分配。
export const HelpDialog: React.FC = () => {
const themeClass = useBehavior(mainStore.themeClass);
const isOpen = useBehavior(mainStore.isHelpDialogVisible);
const [files, setFiles] = useState([]);
const [folderLoading, setFolderLoading] = useState(false);
const InitialState: ITreeNode[] = [];
let currentNode: HelpDTO;
let parentFolder: any = {};
let majorFolder: any = {};
let majorFile: any = {};
useEffect(() => {
if (isOpen) {
fetchHelp();
}
}, [isOpen]);
const fetchHelp = () => {
helpApi.getHelpFiles().then((response) => {
if (response.status !== 200) return;
setFiles(response.data);
checkFileContent();
});
};
return (
<Dialog
className={classNames(themeClass, styles.helpDialog)}
title="Help"
icon="help"
isOpen={isOpen}
onOpened={fetchHelp}
onClose={closeDialogBox}
>
<div style={{ overflowY: "scroll" }}>
{folderLoading ? <HelpTree nodes={setNodes(files)} /> : <Spinner />}
</div>
</Dialog>
);
};
错误从最后一行的第5条开始出现:
{folderLoading ? <HelpTree nodes={setNodes(files)} /> :
贴花节点:
这是树的声明位置:
interface Props {
nodes: ITreeNode[];
}
export interface State {
nodes: ITreeNode[];
}
// use Component so it re-renders everytime: `nodes` are not a primitive type
// and therefore aren't included in shallow prop comparison
export class HelpTree extends React.Component<State, Props> {
constructor(props: Props) {
super(props);
this.state = {
nodes: props.nodes
};
}
render() {
return (
<Tree
contents={this.state.nodes}
onNodeCollapse={this.handleNodeCollapse}
onNodeExpand={this.handleNodeExpand}
onNodeDoubleClick={this.handleNodeDoubleClick}
/>
);
}
}
答案 0 :(得分:0)
错误告诉您setNodes
函数可能返回"undefined"
而不是ITreeNode
。
您可以通过替换以下内容来更改声明树的类型:
interface Props {
nodes: ITreeNode[];
}
与此:
interface Props {
nodes: ITreeNode[] | undefined;
}
或者您可以检查setNodes
以确保它永远不会返回"undefined"