0

在我的组件中,我从 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是。我觉得我在这里错过了一个简单的技巧。非常感谢您的帮助。

4

1 回答 1

2

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

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());
}, []);

出于性能原因,您可能希望记住排序和过滤,以便仅在 、 或更改时groups重新sort运行filter

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]);
于 2020-04-14T18:18:52.020 回答