【问题标题】:Is it bad practice to directly import actions into components?直接将动作导入组件是不好的做法吗?
【发布时间】:2018-09-13 03:26:42
【问题描述】:

这样的做法是不好的吗?

SendInfoButton.js

import React from 'react';
import { sendInfo } from '../actions/index';

export const SendInfoButton = ({currentUser}) => (
    <div>
        <button onClick={() => sendInfo(currentUser)} />
    </div>
)

actions/index.js

import { store } from '../reducers/index';
import { SEND_INFO } from '../constants/index;

export const sendInfo = (currentUser) => store.dispatch({type: SEND_INFO, payload: currentUser})

与使用 mapDispatchToProps 并将操作传递给不会使用它们的组件相比,以这种方式将操作直接导入组件似乎更有效。我也更倾向于导入这样的动作,因为我已经有了带有大量 props 的组件,不想再添加了。

【问题讨论】:

标签: javascript reactjs ecmascript-6 redux


【解决方案1】:

导入动作创建者,如import { sendInfo } from '../actions/index';,很好 - 这就是你应该这样做的方式。

但是,您应该使用connect“绑定”动作创建者,以便他们在运行时访问正确的商店实例并自动分派动作。这可以通过使用“对象速记”语法来缩短 - 只需将一个充满动作创建者的对象作为第二个参数传递给connect,例如:

export default connect(null, {sendInfo})(SendInfoButton);

同样,你shouldn't import the store directly。正如@estes 所说,这将您的代码一直锁定在同一个“生产”存储实例中,并且使测试或重用您的代码变得更加困难。

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 2017-12-28
    • 2014-04-30
    • 1970-01-01
    相关资源
    最近更新 更多