React useState hook not updating state onClick
我在React中使用useState挂钩,当
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | const Map = () => { const [viewport, setViewport] = useState({longitude: -98.58, latitude: 39.83, zoom: 3.5}) const [geojson, setGeojson] = useState(null) useEffect(() => { // GeoJSON const locations = []; let ref = fire.database().ref("...").orderByKey(); ref.once("value", snapshot => { snapshot.forEach(function(childSnapshot) { if (childSnapshot.val().Company !=="") { locations.push(childSnapshot.val()); } if (locations.length === 1219) { var geojson = { type:"FeatureCollection", features: locations.map(item => { return { ... }, geometry: { type:"Point", coordinates: [item.Long, item.Lat] } }; }) }; setGeojson(geojson); return geojson; } }); }) }); const _updateViewport = () => { setViewport(viewport) } const _updateData = () => { const locations = []; let ref = fire.database().ref("...").orderByKey(); ref.once("value", snapshot => { snapshot.forEach(function(childSnapshot) { if (childSnapshot.val().Company !=="" && childSnapshot.val().Size ==="Large") { locations.push(childSnapshot.val()); } if (locations.length === 232) { var geojson = { type:"FeatureCollection", features: locations.map(item => { return { ... }, geometry: { type:"Point", coordinates: [item.Long, item.Lat] } }; }) }; console.log(geojson); setGeojson(geojson); return geojson; } }); }) } return ( <ReactMapGL {...viewport} onViewportChange={_updateViewport} width="100%" height="100%" mapStyle={mapStyle} mapboxApiAccessToken={TOKEN}> <Source type="geojson" data={geojson}> <Layer {...icon} /> </Source> <NavigationControl onViewportChange={_updateViewport} /> <button style={navStyle} onClick={_updateData}>Update</button> </ReactMapGL> ); } export default Map; |
如果只想首次加载,请
像这样使用useEffect:
我建议您改用useReducer钩子,因为useState在让您知道更新时有点问题,我不知道为什么?!