Redux Toolkit:如何将商店更改同步到本地状态?

ReduxToolkit: How to sync store change to local state?

在我的组件中,我从 API 加载初始数据,如下所示:

    const dispatch = useDispatch();
    const groups = useSelector(selectGroups);
    const [localGroupState, setLocalGroupsState] = useState(groups);

    useEffect(() => {
        dispatch(loadAsync());
    }, []);
export const selectGroups = (state: RootState) => state.userGroups.groups;
export const loadAsync = (): AppThunk => dispatch => { 
    dispatch(loading());  
    axios.get('/data', { headers: { 'Authorization': `Bearer ${getToken()}` } })
    .then((axiosResponse: AxiosResponse<MainState>) => {
        dispatch(loaded(axiosResponse.data));
        console.log('all good')
    })
    .catch(() => {
        console.error('no good')
    });    
};

但是 localGroupState 是空的,而 groups 不是。 我觉得我在这里缺少一个简单的技巧。 非常感谢您的帮助。

如果你想对组进行排序和过滤,那么你的本地状态应该是那些排序和过滤条件。排序和过滤的组应该是一个计算值,而不是状态。

const dispatch = useDispatch();
const groups = useSelector(selectGroups);
const [sort, setSort] = useState('ascending');
const [filter, setFilter] = useState('something');

const sortedGroups = [...groups].sort(
  // replace this with whatever your sorting logic is
  sort === 'ascending' ? (a, b) => a - b : (a, b) => b - a
).filter(() => /* some filtering code */);

useEffect(() => {
    dispatch(loadAsync());
}, []);

出于性能原因,您可能希望记住排序和过滤,以便它仅在 groupssortfilter 更改时重新运行:

const sortedGroups = useMemo(() => {
  return [...groups].sort(
    // replace this with whatever your sorting logic is
    sort === 'ascending' ? (a, b) => a - b : (a, b) => b - a
  ).filter(() => /* some filtering code */);
}, [groups, sort, filter]);