这个函数应该被大量重构:
const buttonLoadMore = ({data,type}) =>{
setMaxRange(prevRange => prevRange + 4);
data = data.slice(0,maxRange);
}
当你在这里使用 maxRange 时,你正在设置新状态,而函数本身正在运行,状态不会立即更新,buttonLoadMore 是特定时间的函数。它无法立即获得新的 maxRange,而运行 buttonLoadMore 是否有意义?此外,您不能像常规变量一样通过使用 = 运算符分配新变量来更新 data 状态,您应该将此函数重构为如下所示:
const buttonLoadMore = ({data})=> {
const newMaxRange = maxRange + 4;
setMaxRange(newMaxRange);
const newData = {events: [...data.events.slice(0, newMaxRange)]};
setData({...newData})
}
你也会在这里遇到错误。因为您的getAPIinfo 将data 状态设置为对象{events: events}。我冒昧地尝试在这里重构它。
您的getAPIinfo 在}).catch(e => setData({events:events})); 行中还有一个错误,您在.then 函数中声明的events 变量在此处无法访问。这简直超出了范围。除非您知道 .catch 解析为数据,否则您将在此行中收到错误。
在此处查看此示例:
const promiseFunction = ()=>{
return new Promise<string>((resolve)=>resolve('i like coca cola'))
}
const getter = () => {
promiseFunction()
.then(response => {
const thenVariable = response;
console.log(thenVariable) // i like coca cola
})
.catch(error=>{
console.log(thenVariable) // Error:Cannot find name 'thenVariable'.
})
}
如您所见,.catch() 与.then() 处于不同的范围,因此events 无法在外部使用,因此.catch 函数无法访问events。
通常你会使用 catch 来处理错误。也许在屏幕上显示一行,该错误已经发生,此时无法获取数据。等等。这里有一本很好的书详细解释了所有这些概念:https://github.com/getify/You-Dont-Know-JS
我强烈建议您切换到 typescript,因为您的代码中存在错误,这些错误应该很容易通过类型检查和添加 eslint 配置来避免。