在功能组件中获取更新的state数据时,我面临一个问题。我见过线程,因此建议切换到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}
/>
);
}发布于 2022-08-14 08:43:49
正如useCallback文件中所述(重点是地雷):
传递一个内联回调和一个依赖项数组。
useCallback将返回回调的回传版本,只有当其中一个依赖项更改了时才会进行更改。这在将回调传递到依赖引用相等以防止不必要呈现(例如shouldComponentUpdate)的优化子组件时非常有用。
您的useCallback的依赖数组是空的,这意味着函数永远不会更新,所以您总是得到初始值。将locationOptions添加为依赖项可以解决您的问题。
您还应该扪心自问,这个useCallback是否必要。这是一篇伟大的文章关于这一点的报道。
https://stackoverflow.com/questions/73350201
复制相似问题