1

我是 reactjs 的新手,我收到此错误:“错误:重新渲染太多。React 限制渲染数量以防止无限循环。” 我不知道如何解决它。

const MAPBOX_TOKEN = ''; ///add token here

export default function MapHooks(){
    const [mapping, setMapping] = useState({
        width: 800,
        height: 600,
        longitude: -122.45,
        latitude: 37.78,
        zoom: 14
      });

    function _onViewportChange(mapping){
        setMapping({mapping})
    }

    function _goToNYC() {
        const viewport = {
            ...mapping,
            longitude: 101.7412,
            latitude: 3.1549,
            zoom: 14,
            transitionDuration: 5000,
            transitionInterpolator: new FlyToInterpolator(),
            transitionEasing: d3.easeCubic
        };
        setMapping({viewport}) 

    }

    return (
        <div>
            <button onClick={_goToNYC()}>New York City</button>
            <MapGL
            {...mapping}
            mapStyle="mapbox://styles/mapbox/dark-v10"
            onViewportChange={_onViewportChange()}
            mapboxApiAccessToken={MAPBOX_TOKEN}
            ></MapGL>
        </div>
    );
}

请帮忙,谢谢:)

4

2 回答 2

4

将函数分配给 时不应执行该函数,而onClick应像这样传递它:

<button onClick={_goToNYC}>New York City</button>

如果您在分配时实际调用它,则该函数将执行。在该执行中,您调用setMapping(...),这将触发重新渲染。然后,当按钮呈现时,这将导致该函数再次执行,依此类推->无限循环

于 2020-02-07T03:52:09.093 回答
2

这是最新的源代码。谢谢你 :)

const MAPBOX_TOKEN = ''

export default function MapHooks(){
    const [mapping, setMapping] = useState({
        width: 800,
        height: 600,
        longitude: -122.45,
        latitude: 37.78,
        zoom: 14
      });

    function _goToNYC() {
        const viewport = {
            ...mapping,
            longitude: 101.7412,
            latitude: 3.1549,
            zoom: 14,
            transitionDuration: 5000,
            transitionInterpolator: new FlyToInterpolator(),
            transitionEasing: d3.easeCubic
        };
        setMapping(viewport)            
    }

    return (
        <div style={{borderStyle: "solid"}}>
            <button onClick={_goToNYC}>2BF53E</button>
            <button>406C01</button>
            <MapGL
            {...mapping}
            mapStyle="mapbox://styles/mapbox/dark-v10"
            onViewportChange={setMapping}
            mapboxApiAccessToken={MAPBOX_TOKEN}
            ></MapGL>
        </div>
    );
}
于 2020-02-07T05:11:07.337 回答