尝试使用React,NextJS和Typescript做一些事情。 我遇到了一个问题,我不断得到"x在类型'布尔值上不存在|任何[]'。属性"x"在类型"false".ts(2339("错误中不存在。 我只是不知道将界面放在哪里以显示它正在使用的类型。 谁能帮我? 这是有问题的代码!
文章.js
import React, { FunctionComponent } from 'react'; // we need this to make JSX compile
import useFetch from '../hooks/fetch'
type artProps = {
title: string,
author: string,
date: number
}
type article = {
title: string,
author: string,
date: number
}
export const Articles: FunctionComponent<{artProps}> = () => {
const url = 'http://localhost:4000/kb'
const data = useFetch(url)
console.log(data)
return (
<div>
{data.map(articles) => {
return (<div key={article.id}>
{console.log(article)}
<h2 key={article.id}>{article.title} </h2>
<p key={article.id}>{article.body}</p>
</div>
)
})}
{/* {artProps.map(artProp => {
return (
<div>
<h2>{artProp.title}</h2>
<p>{artProp.author}</p>
</div>
)
})
} */}
</div>
)
}
export default Articles
钩子
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const useFetch = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
console.log('fetch')
axios.get(url)
.then(res => {
if (res.data) {
setData(res.data)
setLoading(false)
}
})
}
, []);
return [data, loading];
};
export default useFetch
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const useFetch = <T>(url: string): [T, boolean] => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
console.log('fetch')
axios.get(url)
.then((res: any) => {
if (res.data) {
setData(res.data)
setLoading(false)
}
})
}
, []);
return [data, loading];
};
export default useFetch
现在将其添加到父组件...
useFetch<ArrayTypeHere>(url)
现在 .map 将推断出正确的类型,无需注释或类型转换。