reactjs - 反应太多的重新渲染
问题描述
我知道关于这个错误有多个问题,但我试图为这个特定问题找到解决方案。
在子组件中,我获取用户的地理位置并在数据到达时返回一个对象。
export default () => {
const [location, setLocation] = useState({
loaded: false,
coordinates: { lat: "", lng: "" },
});
const onSuccess = (location) => {
setLocation({
loaded: true,
coordinates: {
lat: location.coords.latitude,
lng: location.coords.longitude,
},
});
};
const onError = (error) => {
setLocation({
loaded: true,
error: {
code: error.code,
message: error.message,
},
});
};
useEffect(() => {
if (!("geolocation" in navigator)) {
onError({
code: 0,
message: "Geolocation not supported",
});
}
navigator.geolocation
.getCurrentPosition(onSuccess, onError)
}, []);
return location;
};
在我的父组件中,我想使用 React hooks 更新我的状态
import { LocateUser } from "../components";
export default () => {
const [userPos, setUserPos] = useState({ lat: "", lon: "" });
const location = LocateUser();
if (location.loaded) {
console.log(location.coordinates.lat);
setUserPos({ // this creates the error
lat: location.coordinates.lat,
lon: location.coordinates.lng,
});
}
return (
<React.Fragment>
{ location.loaded ? JSON.stringify(location) : 'No location found' }
</React.Fragment>
);
}
我已经尝试过使用 useEffect 和其他解决方法,但没有找到使其工作的解决方案。问题是第一次加载子组件时,地理位置响应为空,稍后它会返回带有数据的对象。从子组件获取响应并更新父组件状态的解决方案是什么?提前致谢
解决方案
包装useEffect
另一个
useEffect(() => {
if (location.loaded) {
console.log(location.coordinates.lat);
setUserPos({
lat: location.coordinates.lat,
lon: location.coordinates.lng,
});
}
}, [location]) // location inside dependency array of the side effect
以便对似乎是自定义挂钩的location
返回的更新进行LocateUser()
“侦听”并调用副作用来更新父组件的状态。
推荐阅读
- javascript - 加载外部 JS 不影响 TTI
- node.js - 无法在 Node.js 中解析 HTTP 响应正文
- java - 未选中的方法 'sort(List
)' 在 Java 11 中使用泛型调用 - sql - 如何解决 db2 代码:-104,SQL 状态:42601
- html - 如何在不使用背景图像属性的情况下覆盖图像英雄?
- javascript - 使用基于标题搜索的 JavaScript 修改 JSON 对象
- highcharts - 如何更改highchart中区域多边形的线宽?
- amazon-web-services - 应用程序负载均衡器 AWS 的 400 握手错误(Flask 和 Socket.io)
- tiles - 将 rasterize=True 与 datashader 一起使用时,如何在 count=0 的情况下获得透明度以查看底层图块?
- reactjs - 避免使用 Styled Components 和 Typescript 传递 props