【问题标题】:Where to put useDispatch and bindActionCreators in a project?在项目中将 useDispatch 和 bindActionCreators 放在哪里?
【发布时间】:2022-01-06 11:30:27
【问题描述】:

我的问题是这个,我把上面提到的方法放在哪里?因为在我想在其中使用 Redux 存储的每个组件中,我基本上都需要重复的口头禅,

import { useSelector, useDispatch } from "react-redux";
import { bindActionCreators } from "redux";
import * as actions from "../../redux/actions";

然后,例如,

const dispatch = useDispatch();
const { fetchStats } = bindActionCreators(actions, dispatch);

我看到有些人制作了containers 之类的文件夹?

另外,你的文件结构是什么?你们把动作放在哪里?你如何导出它们?全部在一个文件中还是什么?在更大的项目中,它并不是很有效。

一如既往,提前致谢!

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    答案是,不要。

    bindActionCreators 实际上只在 React-Redux 内部使用过 connect 函数,通常不被应用程序代码使用。

    今天,使用 React-Redux 钩子 API,我们建议只手动编写:

    const dispatch = useDispatch();
    const handleClick = () => dispatch(someActionCreator())
    

    这样可以更清楚地了解组件中实际发生的情况。

    是的,这确实需要将钩子导入到组件中。就像任何其他功能一样,使用它们既是有意的也是必要的。

    我们建议反对尝试分离出“容器组件”,尤其是在您使用 hooks API 时。

    至于逻辑,您应该使用"feature folder" file structure using Redux Toolkit to create one "slice" file per feature containing the logic

    【讨论】:

    • 非常感谢。所以提供的链接列出了 Redux 的推荐文件结构,对吧?
    • 我需要使用工具包吗?
    • 如何编写 Redux 逻辑与这个关于 React-Redux 的问题是分开的。但是,是的,您应该使用 Redux Toolkit,因为它现在是编写 Redux 逻辑的标准方法,并将大大简化您的代码:redux.js.org/style-guide/…
    • 谢谢你,朋友!
    猜你喜欢
    • 2018-07-14
    • 2020-09-02
    • 2018-09-13
    • 1970-01-01
    • 2012-11-07
    • 2017-06-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多