gpt4 book ai didi

reactjs - React + Redux - 在dumb组件中调度一个 Action ?

转载 作者:行者123 更新时间:2023-12-03 13:58:07 24 4
gpt4 key购买 nike

我开始学习 Redux,整个想法看起来很简洁,但是在将我的 React 应用程序从“正常”重建为“redux-way”后,这个问题出现了。

我有一个基于来自异步调用的 JSON 构建的 if 项目列表。然后该列表中的每个项目都会在单击时发送异步调用并返回一些内容。

之前我的应用程序非常简单:

components/list/List.jsx
components/list/ListItem.jsx

现在看起来像这样:

footer/list/ListContainer.jsx // here I run an async call and generate list
footer/list/List.jsx // dumb component creating the whole list full of ListItemContainer components as <li>
footer/list/ListItemContainer.jsx // here I run another async for each <li>
footer/list/ListItem.jsx // dumb component containing <li>

在我看来,这要复杂得多,但还有另一个问题。

每次我点击我的<li>我想触发一个 Action 然后做一些事情,我的问题是:我可以在 ListItem.jsx 中做到这一点吗?我不这么认为,因为它是一个愚蠢的组件?

这是我现在的 ListItem.jsx:

import React from 'react';
import { connect } from 'react-redux';

// some other imports

class ListItem extends React.Component {

render(props) {
return (
<li>
<a href="#" onClick={//can I do something here?//}>
{this.props.contents}
</a>
</li>
)
}
}

export default ListItem;

最佳答案

只需将点击处理程序传递给您的dumb组件即可。dumb组件只是一个不关心它所获取的 props 来源的组件。这并不意味着它不能调用函数或任何东西。我们以这种方式拆分它们的原因是,我们可以在其他地方重用从不同来源获取 Prop 的dumb组件。

@bennygenel 的回答大部分都很好,所以我不知道他为什么删除它。

这就是我要做的:

ListItem.js:

// Dumb component (very re-usable)

const ListItem = props => (
<li>
<a href="#" onClick={props.onClick}>
{props.contents}
</a>
</li>
);

export default ListItem;

ListItemContainer.js:

// Smart component
import action from 'someAction';

const mapStateToProps = (state) => ({
contents: state.something.contents,
});

const mapDispatchToProps = {
onClick: action,
};

export default connect(mapStateToProps, mapDispatchToProps)(ListItem);

我们在mapDispatchToProps中绑定(bind)onClick处理程序,这会自动将处理程序包装在调度中,以便当用户单击列表项时它会正确调度。

如果您不想或看不到需要,您不必将其拆分,但现在我们可以将 ListItem 重新用于其他点击处理程序,因为它不依赖于分派(dispatch)特定操作,props.content 并不与特定状态绑定(bind),因为我们也将其拆分到容器中。

关于reactjs - React + Redux - 在dumb组件中调度一个 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120630/

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