【问题标题】:Using React, how can I update state from inside a custom function?使用 React,我如何从自定义函数内部更新状态?
【发布时间】:2019-07-25 19:25:43
【问题描述】:

我正在尝试将 React Hooks 与 Google Places API 一起使用来自动完成位置搜索,找到该位置的 Google Place ID,然后使用该值更新我的组件状态。

我的 Google API 工作正常,我能够获取地点 ID,但我不确定如何从我的功能更新我的状态。


function onMapsLoad() {
  // init autocomplete
  const autocomplete = new window.google.maps.places.Autocomplete(document.getElementsByClassName('search')[0]);

  autocomplete.addListener('place_changed', function() {
    // define place and place ID
    const place = autocomplete.getPlace();
    const placeID = place.place_id;

    // how can I update the component state from inside this function?
  });
}

function myComponent() {
  const [placeID, setPlaceID] = useState(null);

  useEffect(() => {
    const script = document.createElement(`script`);
    const headScript = document.getElementsByTagName(`script`)[0];

    script.type = `text/javascript`;
    script.src = `https://maps.google.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}&libraries=places`;

    script.addEventListener('load', onMapsLoad);
  });
);
}

【问题讨论】:

    标签: reactjs state react-hooks


    【解决方案1】:

    要么在组件内移动函数(从而使 setPlaceID 在范围内):

    function myComponent() {
      const [placeID, setPlaceID] = useState(null);
    
      function onMapsLoad() {
        // ... same as before, but then ending with a call to:
        setPlaceID(placeID);
      }
    
      useEffect(() => {
        // ...
      });
    }
    

    或者将setPlaceID作为参数传入

    function onMapsLoad(setPlaceID) {
        // ... 
        setPlaceID(placeID);
    }
    
    function myComponent() {
      const [placeID, setPlaceID] = useState(null);
    
      useEffect(() => {
        // ... same as before, except the last line:
        script.addEventListener('load', () => onMapsLoad(setPlaceID));
      });
    }
    

    【讨论】:

    • 当然,现在我看到了这一点。非常感谢你!您能想到这两种方法的优缺点吗?
    • 我通常推荐第一个选项。每次渲染组件时它都会创建一个新函数,这意味着其闭包中的值始终与组件保持同步。这确实意味着每次渲染都会创建一个新函数。创建一个函数的时间是微不足道的(大约纳秒),所以不要担心这个方面。但是,如果您将此函数传递给子组件,则更改函数可能会破坏子组件的 shouldComponentUpdate。如果发生这种情况,您可以使用 useMemo 或 useCallback。见:reactjs.org/docs/hooks-reference.html#usecallback
    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2021-04-19
    相关资源
    最近更新 更多