[英]Why wont my object re-render after updating the object's state?
I'm trying to iterate through my json to create an infinite scroll.我正在尝试遍历我的 json 以创建无限滚动。 On load, I'm showing the first 2 records.
在加载时,我正在显示前 2 条记录。 When someone scrolls to the bottom of the page I'm trying to update my object to show current 2 records and append next 2 records to the object.
当有人滚动到页面底部时,我正在尝试更新我的 object 以显示当前 2 条记录和 append 下 2 条记录到 object。
I've tried updating the object's state by merging the current object and a new object with the next two records but I keep getting "TypeError: newData.map is not a function" I've tried updating the object's state by merging the current object and a new object with the next two records but I keep getting "TypeError: newData.map is not a function"
function Cards() {
const [roomsData, setroomsData] = useState([]);
const [prevData, setprevData] = useState([]);
const [newData, setnewData] = useState([]);
const [nextData, setnextData] = useState([]);
const [startIndex, setstartIndex] = useState(0);
const [lastIndex, setlastIndex] = useState(2);
useEffect(() => {
axios.get(`/data/rooms.json`)
.then(res => {
const roomDataRes = res.data;
setroomsData(roomDataRes);
setprevData(roomDataRes.slice(startIndex,lastIndex));
setnewData(roomDataRes.slice(startIndex,lastIndex));
})
}, []);
//detect end of page scroll
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
//what happens after end of page scroll
function handleScroll() {
if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight) return;
setnextData(newData.slice(2,4));
setnewData({...prevData,...nextData});
}
const cards = newData.map((item,index) =>
<Card key={index}
id={item.id}
roomname={item.roomname}
location={item.location}
zipcode={item.zipcode}
images={[item.images]}
profile={item.profile}
price={item.price}
bullets={[item.bullets]}
/>
);
return (
<div className="cardcontainer">
{cards}
</div>
);
}
export default Cards;
When you scroll to the bottom of the page I'm expecting the cards to update to show the current records and also the next two records, but when you scroll to the bottom I keep getting on the re-render: TypeError: newData.map is not a function当您滚动到页面底部时,我希望卡片会更新以显示当前记录以及接下来的两条记录,但是当您滚动到底部时,我会继续重新渲染: TypeError: newData.map不是 function
The problem is that you're changing newData
to an object问题是您将 newData 更改为
newData
setnewData({...prevData,...nextData})
use利用
setnewData([...prevData,...nextData])
instead.反而。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.