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



我在获取功能组件中更新的state数据时遇到问题。我在SO上看到过一些线程,建议切换到Class组件,在该组件中,不使用钩子就可以更好地管理状态,但我觉得功能组件中的钩子也可以。

我的代码如下

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}
/>
);

}

useCallback(强调矿(文件中所述:

传递一个内联回调和一个依赖项数组。useCallback将返回回调的记忆版本,该版本只有在其中一个依赖项发生更改时才会更改。当将回调传递给依赖引用相等的优化子组件以防止不必要的渲染(例如shouldComponentUpdate(时,这很有用。

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

您还应该问问自己这个useCallback是否有必要。这是一篇关于这方面的好文章。

最新更新