虽然我有几年的普通Javascript经验,但我对打字本还是很陌生的。这是我第一个使用Next.js构建的完整程序。我只是对我可以改进的地方感到好奇,尤其是在接口方面。
import type { NextPage } from 'next'
import { useEffect, useState } from 'react'
interface QuoteProps {
image?: string, quote?: string, character?: string
}
interface QuoteArray {
image: string, quote: string, character: string
}
function QuoteComponent(props: QuoteProps){
return(
<div>
<img src={props.image} />
<p>{props.quote}</p>
<span>{props.character}</span>
</div>
)
}
const Home: NextPage = () => {
const [quoteData, setQuoteData] = useState<QuoteArray>()
const [loading, setLoading] = useState(true)
const [filterString, setFilterString] = useState('')
const handleFetch = () => {
let url;
filterString.length > 1 ?
url = 'https://thesimpsonsquoteapi.glitch.me/quotes?character='+filterString :
url = 'https://thesimpsonsquoteapi.glitch.me/quotes'
fetch(url)
.then(response => response.json())
.then((data) => setQuoteData(data['0']))
.catch((error) => console.error(error))
.finally(() => setLoading(false))
}
//We load a random quote on page load
useEffect(() => {
handleFetch()
}, [])
return (
<>
{
loading ?
<p>Loading...</p> :
<>
<QuoteComponent
image={quoteData?.image}
quote={quoteData?.quote}
character={quoteData?.character}
/>
<input placeholder='Filter by character name' onChange={(e) => { setFilterString(e.target.value) }} />
<button onClick={handleFetch}>New quote</button>
</>
}
</>
)
}
export default Home发布于 2022-10-12 08:34:12
由于QuoteArray和QuoteProps实际上是相同的(Quoteprops是QuoteArray的一个可选子集),所以可以使用Partial关键字。
interface QuoteArray {
image: string,
quote: string,
character: string
}
function QuoteComponent(props: Partial<QuoteArray>){...}部分构造一个Type,并将Type的所有属性设置为可选。此实用程序将返回一个类型,该类型表示给定类型的所有子集。
您还可以导出接口,这样它就可以在其他组件中重用。每当出现这种需要时,创建类型文件的问题取决于您正在编写的内容。
发布于 2022-10-20 22:45:32
几点想法:
QuoteComponent不需要使用可选属性并防止其缺位。类型记录允许您在您的编码更明确。相反,让他们需要。你可以在打电话的人中只写一个守卫。QuoteArray)。这样叫起来就容易了。它从页面类中删除了所有细节,这很好。handleFetch为不同的东西,因为它并不是在“处理”获取.它只是在做一个。它正在处理一个“新报价请求”,所以我会用它作为名称。如果您想根据它所做的命名它,它只是fetchNewQuote (也很好),它将是按钮的onClick处理程序。loading只在组件第一次呈现时才被设置为true,因此它很可能可以通过查找引用数据的存在来替换.虽然有点挑剔..。您可能想在您的setLoading中执行一个useEffect调用--尽管这样做会变得很复杂,以确定时间安排。发布于 2022-10-07 00:34:46
我喜欢做的是有一个专门的文件夹类型。在这里,我可以在整个项目中重用它。
尽管在您的界面中,您编写了两次相同的代码。
您只需扩展另一个接口来重用它。
希望这能帮上忙!
https://codereview.stackexchange.com/questions/280012
复制相似问题