【发布时间】:2021-09-27 16:23:26
【问题描述】:
我在将 Typescript 添加到我的 React 代码中时遇到了很多问题,特别是使用 useSate 钩子。
过去几天我一直在研究如何解决这个问题,但我不确定需要将什么传递给钩子。我应该创建一个单独的.ts 文件来存储我期望在挂钩中的内容吗?当我滚动到带下划线的错误时,它会不断显示如下错误:
“Map”类型的参数不能分配给“SetStateAction”类型的参数。 类型 'Map' 与签名 '(prevState: undefined): undefined' 不匹配。
或
类型 '{ children?: ReactNode; 上不存在属性 'features' }'.`
我已包含我的代码以提供更好的视角,并从我正在使用的源代码中保留在 cmets 中。
import { FC } from "react";
import { useState, useEffect, useRef } from "react";
import "./mapwrapper.css";
// openlayers
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import XYZ from "ol/source/XYZ"; //here...
import { fromLonLat } from "ol/proj";
const Home: FC<{}> = (props) => {
// set intial state
const [map, setMap] = useState();
const [featuresLayer, setFeaturesLayer] = useState();
// pull refs
const mapElement = useRef<HTMLDivElement>(null);
// create state ref that can be accessed in OpenLayers onclick callback function
// https://stackoverflow.com/a/60643670
const mapRef = useRef<{}>();
mapRef.current = map;
// initialize map on first render - logic formerly put into componentDidMount
useEffect(() => {
// create and add vector source layer
const initalFeaturesLayer = new VectorLayer({
source: new VectorSource(),
});
const seoul = [126.97794, 37.56629];
const seoulWebMercator = fromLonLat(seoul);
// create map
const initialMap = new Map({
target: mapElement.current!,
layers: [
// Google Maps Terrain
new TileLayer({
source: new XYZ({
url: "http://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}",
}),
}),
initalFeaturesLayer,
],
view: new View({
projection: "EPSG:3857",
center: seoulWebMercator,
zoom: 16,
}),
controls: [],
});
// save map and vector layer references to state
setMap(initialMap);
setFeaturesLayer(initalFeaturesLayer);
}, []);
// update map if features prop changes - logic formerly put into componentDidUpdate
useEffect(() => {
if (props.features.length) {
// may be null on first render
// set features to map
featuresLayer.setSource(
new VectorSource({
features: props.features, // make sure features is an array
})
);
// fit map to feature extent (with 100px of padding)
map.getView().fit(featuresLayer.getSource().getExtent(), {
padding: [100, 100, 100, 100],
});
}
}, [props.features, featuresLayer, map]);
return (
<div>
<div ref={mapElement} className="map-container"></div>
</div>
);
};
export default Home;
【问题讨论】:
标签: reactjs typescript use-state