我仍然是使用ReactJS的初学者,我不理解我遇到的问题.
我的useEffect
是一个数据列表,然后我做filter
.
但是当我保存这个过滤器的数据值时,我try 用console.log()
来查看我的过滤器的返回值,有一个无限循环的数据被加载,我不明白为什么会发生这种情况.
有人能帮我吗?
这是我的代码,更容易理解我的意思:
我把我的密码输入codesandbox
import React, { useRef } from "react";
import { Map, TileLayer } from "react-leaflet";
import { getAccommodations } from "./data";
import "./styles.css";
const App = () => {
const center = [-27.592495455704718, -48.484572875610034];
const mapRef = useRef();
const [thing, setThing] = React.useState(0);
const [accommodationData, setAccommodationData] = React.useState([]);
React.useEffect(() => {
if (mapRef.current) {
const response = getAccommodations();
const _response = response.filter((accommodation) => {
return mapRef.current.leafletElement
.getBounds()
.contains([accommodation.listing.lat, accommodation.listing.lng]);
});
setAccommodationData(_response);
}
}, [center, thing, accommodationData]);
// I commented this line to avoid too many re-renders
// console.log("accommodationData: ", accommodationData);
return (
<Map
ref={mapRef}
style={{ width: "100%", height: "100vh" }}
center={center}
zoom={13}
onmoveend={() => {
setThing(thing + 1);
}}
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{/* I'll add some <Markers> here with the accommodationData array */}
</Map>
);
};
export default App;
非常感谢