TypeError: startDate.getTime不是一个函数


const [startDate, setStartDate] = useState(new Date());  

const apiCall = () => {
let timeStamp = Number(startDate.getTime());
axios.get(
`https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD,EUR&ts=${timeStamp}&extraParams=ProfitsCrypto`
)
.then((res) => {
console.log(res.data);
});
};

你好,我有一些问题与反应,我试图使用getTime,因为我想要一个时间戳来使用api,我可以用console.log(startDate.getTime()),但错误是TypeError: startDate.getTime is not a function.

有人能帮我吗?谢谢你。

我认为你必须检查什么是startDate变量的dataType,当你使用它。我认为它的类型或值在代码的某个地方发生了变化。你应该共享你的代码。

你看到这个错误是因为你实例化apiCall闭包函数的那一刻,startDate的引用还没有被useState()初始化为你提供的值new Date()

解决这个问题的方法是用一个useCallback()React钩子包装你的apiCall方法,并提供你的值startDate作为依赖项。这样,每次startDate值更改时,您的apiCall方法将按预期工作。

const [startDate, setStartDate] = useState(new Date());  

const apiCall = useCallback(() => {
let timeStamp = Number(startDate.getTime());
axios.get(
`https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD,EUR&ts=${timeStamp}&extraParams=ProfitsCrypto`
)
.then((res) => {
console.log(res.data);
});
}, [startDate]); // note the dependency reference here

最新更新