首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取功能组件中的更新状态数据

获取功能组件中的更新状态数据
EN

Stack Overflow用户
提问于 2022-08-14 08:35:09
回答 1查看 24关注 0票数 -1

在功能组件中获取更新的state数据时,我面临一个问题。我见过线程,因此建议切换到Class组件,在那里可以更好地管理状态,而无需使用钩子,但我觉得功能组件中的钩子也应该是一样的。

我的代码如下

代码语言:javascript
复制
function HomePage(){
    const [selected, setSelected] = useState({});
    const [locationOptions, setLocationOptions] = useState([
        {label: 'Location 1', value: 'location-1'},
        {label: 'Location 2', value: 'location-2'},
        {label: 'Location 3', value: 'location-3'},
    ]);


    // Getting the data from the servers and updating the state
    // works fine in the render, the data gets updated
    const { data: locationData, refetch: locationDataRefetch } = useAppQuery({
        url: "/api/get-locations", 
        reactQueryOptions: {
            onSuccess: async ( e ) => {
              if ( e.data ) {
                setLocationOptions( e.data );
              } else {
                // handle errors
              }
            },
          },
      });

    
    const seeUpdatedLocations = () => {
        // This is where the problem is, even after the state is updated after getting
        // the data from the API, this still logs the initial value of locationOptions
        console.log( locationOptions );
    }


    const handleSelectChange = useCallback((value) => {
        // This is where the problem is, even after the state is updated after getting
        // the data from the API, this still logs the initial value of locationOptions
        // value can be 'location-1', and I use lodash to get the right object from locationOptions
        let selectedLocationObj = _.find( locationOptions, ( o ) => o.value == value );

        console.log( selectedLocationObj ); // Doesn't work as the locationOptions doesn't contain the real values received from API

    }, []);


    return (

        <Select
                label="Location"
                options={locationOptions}
                onChange={ handleSelectChange }
                value={ selected.value }
                labelHidden={true}
        />

    );



}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-14 08:43:49

正如useCallback文件中所述(重点是地雷):

传递一个内联回调和一个依赖项数组。useCallback将返回回调的回传版本,只有当其中一个依赖项更改了时才会进行更改。这在将回调传递到依赖引用相等以防止不必要呈现(例如shouldComponentUpdate)的优化子组件时非常有用。

您的useCallback的依赖数组是空的,这意味着函数永远不会更新,所以您总是得到初始值。将locationOptions添加为依赖项可以解决您的问题。

您还应该扪心自问,这个useCallback是否必要。这是一篇伟大的文章关于这一点的报道。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73350201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档