【发布时间】:2020-05-21 18:08:45
【问题描述】:
我正在使用 ReactHook 开发项目,但 React.createRef() 有问题。我遇到了这个问题,我想知道这种情况叫什么?以及如何解决?如图 1 所示,当我点击查看时,它显示对象的值为 null。那里有值,但我无法通过键访问它的值,因为我无法访问 null 的键。
图1.我尝试console.log变量googleMap后
import { Map, GoogleApiWrapper } from "google-maps-react";
import { GOOGLE_API_KEY } from "../../key.js";
const storePage = ({google}) => {
const googleMap = React.createRef();
console.log(googleMap.current.map);
...
图2.我只是使用React.createRef()来访问组件
...
return (
<Map
google={google}
zoom={16}
initialCenter={{ lat: yourLocation.lat, lng: yourLocation.lng }}
style={{ height: "20rem" }}
ref={googleMap}
></Map>)
}
const enhance = compose(
GoogleApiWrapper({ apiKey: GOOGLE_API_KEY }),
connect(mapStateToProps, mapDispatchToProps)
);
export default enhance(StorePage);
图 3.我想访问组件以获取如图 1 所示的值
图 4.但是当我通过键访问值时(比如这个googleMap.current.map),就会出现这个图的错误
【问题讨论】:
-
这是一个类还是一个函数组件?在您使用 console.log 时,组件可能尚未呈现。在 DOM 中呈现之前,它不会有任何值。如果您在类组件中,则可以在 componentDIdMount 生命周期中捕获它。如果它是一个功能组件,您可以在 useEffect 挂钩中执行此操作
-
一个函数组件
-
请不要显示代码图片。显示代码。 Stackoverflow has straight-forward markup for this
标签: javascript reactjs object react-hooks ref