收到此错误“错误:重新渲染太多。React限制了渲染数量以防止无限循环。”

时间:2020-02-07 03:46:17

标签: reactjs react-hooks react-map-gl

我是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>
    );
}

请帮助,谢谢:)

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分: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>
    );
}