按照高层元器件厂的官方引用更新控件组件的道具
核心API导出其他可以以类似方式使用的高水平部件工厂。
我模仿了这个例子--但是我得到了以下语法错误:
import L from "leaflet";
import "leaflet-routing-machine";
import { createControlComponent } from "@react-leaflet/core";
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css'
function setWaypoints(props)
{
return {
waypoints: [
L.latLng(props.startLat, props.startLng),
L.latLng(props.endLat, props.endLng)
],
lineOptions: {
styles: [{ color: "#0500EE", weight: 4 }]
},
show: false,
addWaypoints: false,
routeWhileDragging: true,
draggableWaypoints: true,
fitSelectedRoutes: true,
showAlternatives: false,
createMarker: function() { return null; },
}
}
function createRoutingMachine(props, context)
{
const instance = new L.Routing.control(setWaypoints(props))
return
{
instance, context: { ...context, overlayContainer: instance }
}
}
function updateRoutingMachine(instance, props, prevProps)
{
if (props.endLat !== prevProps.endLat || props.endLng !== prevProps.endLng)
{
instance.setWaypoints(props)
}
}
const RoutingMachine = createControlComponent(createRoutingMachine, updateRoutingMachine)
export default RoutingMachine;失踪的分号。(35:25) 33 %返回34 %{ 35实例,上下文:{ ...context,overlayContainer: instance } \x{e76f}
如果我把这个改为:
function createRoutingMachine(props)
{
const instance = new L.Routing.control(setWaypoints(props))
return instance
}编译器很高兴,但是组件从不更新。
我知道我创建的Control组件不正确,但是我找不到正确实现的信息。
相关信息:
发布于 2021-05-24 14:30:41
您将注意到,在文档中,createcontrolcomponent只列出了一个参数,即创建实例的函数。您期望它的行为类似于createlayercomponent,其中包含两个参数。在createlayercomponent中,第二个参数是在道具更改时更新层组件的函数。然而,createcontrolcomponent没有提供这样的功能。反应-传单是假设,很像香草传单,一旦你的控制被添加到地图,你将不需要直接改变它。
这在传单路由机方面有点混乱,因为您不需要更改控件的实例,而是需要调用影响地图显示的方法。
IMO,最好的方法是使用一个状态变量来跟踪您的路径点是否发生了变化,并使用ref访问路由机的底层传单实例,并调用setWayPoints:
// RoutineMachine.jsx
const createRoutineMachineLayer = (props) => {
const { waypoints } = props;
const instance = L.Routing.control({
waypoints,
...otherOptions
});
return instance;
};
// Takes only 1 argument:
const RoutingMachine = createControlComponent(createRoutineMachineLayer);// Map.jsx
const Map = (props) => {
// create a ref
const rMachine = useRef();
// create some state variable, any state variable, to track changes
const [points, setPoints] = useState(true);
const pointsToUse = points ? points1 : points2;
// useEffect which responds to changes in waypoints state variable
useEffect(() => {
if (rMachine.current) {
rMachine.current.setWaypoints(pointsToUse);
}
}, [pointsToUse, rMachine]);
return (
<MapContainer {...props}>
<RoutineMachine ref={rMachine} waypoints={pointsToUse} />
<button onClick={() => setPoints(!points)}>
Toggle Points State and Props
</button>
</MapContainer>
);
};额外好处:迫使<RoutineMachine>组件(或任何react )重新安装的一个廉价而简单的方法是给它分配一个key支柱,并在您想要重新修改它时更改它。这可能是一个uuid,甚至是通过JSON.stringify运行的一组唯一的路径点。只是个主意。
https://stackoverflow.com/questions/67671931
复制相似问题