gpt4 book ai didi

reactjs - 是否可以在 React Hooks 中对 useReducer 的调度进行回调?

转载 作者:行者123 更新时间:2023-12-03 13:42:36 25 4
gpt4 key购买 nike

const handleFilter = (filter_type, selection) => {
dispatch({ type: filter_type, option: selection.option })
filterData()
}

我有一个 useReducer 来处理选定的过滤器。我必须调用 filterData 来根据所选过滤器过滤数据。

但是,由于不能保证 filterData 在调度后发生,因此我不断收到状态延迟更新。

我也尝试过

const handleFilter = (filter_type, selection) => {
dispatch({ type: filter_type, option: selection.option })
.then(filterData())
}

但这给了我一个错误无法读取未定义的属性“then”

有什么帮助吗?

编辑

useEffect(() => {
const urls = [
'http://.../v1/profiles',
];
const fetchJson = url => fetch(url, get_options).then(res => res.json());
Promise.all(urls.map(fetchJson))
.then(([profile]) => {
setFilteredTable(profile.result)
})
.catch(err => {
console.log(err)
});
}, []);

const init_filter = { TITLE: '', LOCATION: '' }

const [filter, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'TITLE':
return { ...state, TITLE: action.option }
case 'LOCATION':
return { ...state, LOCATION: action.option }
case 'RESET':
return init_filter
default:
return state
}
}, init_filter)

最佳答案

I have to call the filterData which filters the data based on the selected filter.

当你描述一个监听器时,你可以尝试使用 useEffect钩子(Hook):

const [filter, dispatch] = useReducer(optionsReducer, initialValue);

useEffect(() => {
filterData();
}, [filter]);

const handleFilter = (filter_type, selection) => {
dispatch({ type: filter_type, option: selection.option });
};

关于reactjs - 是否可以在 React Hooks 中对 useReducer 的调度进行回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com