【问题标题】:Is it possible to put a callback to useReducer's dispatch in React Hooks?是否可以在 React Hooks 中对 useReducer 的调度进行回调?
【发布时间】:2020-02-26 05:56:03
【问题描述】:
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())
}

但这给了我一个错误Cannot read property 'then' of undefined

有什么帮助吗?

编辑

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)

【问题讨论】:

  • 你不能只是将then 添加到函数中并希望得到结果
  • reducer中不能调用filterdata吗?

标签: reactjs react-hooks


【解决方案1】:

我必须调用filterData,它根据所选过滤器过滤数据。

你描述了一个监听器,你可以尝试使用useEffect钩子:

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

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

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

【讨论】:

  • 你能检查一下我的编辑吗?我使用useEffect 从数据库中获取数据。我不确定如何使它仅适用于过滤器的更改。
  • 你可以使用多个useEffects,上面的监听器在filter变化上运行,尝试阅读文档。
  • 哦,我不知道多个useEffects 是可能的。现在可以了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多