我正在寻找一个解决方案,这样我可以把getFavList
个函数在服务
文件中.但是,因为涉及到setAllData
.我真的不能对如何做到这一点心中有数.以下是原始代码.
Index.tsx
export default function FavoriteList() {
const [allData, setAllData] = useState<Data[]>([])
const [hasUpdated, setHasUpdated] = useState<Boolean>(true)
const getFavList = async () => {
await axios.get(`${API}/api/favCharityList`)
.then((res => {
let arr = []
arr = [...res.data.charities]
setAllData(arr)
}))
.catch(err => console.error(`Error: ${err}`))
}
useEffect(() => {
getFavList();
}, [hasUpdated])
return (
<></>
)
}
我试着把它放在一个单独的文件里.但是,第setAllData
行返回错误.
错误讯息
Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction<[]>'. Type 'any[]' is not assignable to type '(prevState: []) => []'. Type 'any[]' provides no match for the signature '(prevState: []): []'.
new Index.tsx
export default function FavoriteList() {
const [allData, setAllData] = useState<Data[]>([])
const [hasUpdated, setHasUpdated] = useState<Boolean>(true)
const getFavList = async () => {
await axios.get(`${API}/api/favCharityList`)
.then((res => {
let arr = []
arr = [...res.data.charities]
setAllData(arr)
}))
.catch(err => console.error(`Error: ${err}`))
}
useEffect(() => {
getFavList({ API, setAllData });
}, [hasUpdated])
return (
<></>
)
}
服务
interface AxiosArg {
API: string
setAllData: Dispatch<SetStateAction<[]>>
}
const getFavList = async ({ API, setAllData }: AxiosArg) => {
await axios.get(`${API}/api/favCharityList`)
.then((res => {
let arr = []
arr = [...res.data.charities]
setAllData(arr)
}))
.catch(err => console.error(`Error: ${err}`))
}
export { getFavList }