草庐IT

javascript - 将嵌套的 Redux 智能组件与 reducer 连接起来

coder 2024-07-16 原文

与 Redux 的 ToDo 示例类似,我的项目结构也类似——只是一个容器,其中包含要显示的子组件数组。该商店将如下所示:

{
    workspace: {
        widgets: [1, 2, 3]
    }
    widgets: {
        1: {
            id: 1,
            title: 'First Widget',
            lastPrice: 123.324,
            lastUpdate: '2015-11-12'
        },
        2: {
            id: 2,
            title: 'Second Widget',
            lastPrice: 1.624,
            lastUpdate: '2015-11-12'
        },
        3: {
            id: 3,
            title: 'Third Widget',
            lastPrice: 4.345,
            lastUpdate: '2015-11-12'
        }
    }
}

每个小部件项目本身就是一个复杂的组件 - 许多可能的操作、许多属性和许多子dumb组件。因此,我让每个小部件都成为一个连接的智能组件,带有专用的 WidgetReducer 以保持这些状态更改独立。

我希望 WidgetReducer 一次只关注一个小部件,因此它处理的状态将只是一个单独的小部件节点,例如:

{   id: 3,
    title: 'Third Widget',
    lastPrice: 4.345,
    lastUpdate: '2015-11-12'
}

我的 Workspace 组件目前遍历所有 Widget,将 Widget ID 传递给每个 Widget 智能组件:

@connect(state => ({ workspace: state.workspace }))
export default class Workspace extends React.Component {
    render() {
        return (
            <div>
                {this.props.workspace.widgets.map(id =>
                    (<Widget key={id} widgetId={id} />)
                )}
            </div>
        );
    }
}

我的Widget组件是这样的:

@connect((state, ownProps) => ({ widget: state.widgets[ownProps.widgetId]}))
export default class Widget extends React.Component {
    componentWillMount() {
        this.props.dispatch(subscribeToUpdates(this.props.widgetId));
    }

    render() {
        return (
            <div>
                <header>{this.props.widget.title}</header>
                <div> /* Other widget stuff goes here */</div>
            </div>
        );
    }
}

我如何连接每个 Widget 组件,以便它只接收关于它自己的 Widget 对象的状态更新,并且连接的 Widget Reducer 只关心单个 Widget 对象,而不是它们的集合?

最佳答案

首先看一下Reselect: https://github.com/rackt/reselect

如果我理解这个问题,这就是您要查找的内容。 假设 widget-id 2 的状态发生变化,widget 1 和 widget 3 不关心 widget-id 2 的状态发生变化。只有小部件 2 需要反射(reflect)该更改。 Reselect 使您能够构建“记忆化”的选择功能。 This may sound like a fancy word, but in practice it means that only if the input value of a selector changes, it'll calculate the next state.

在小部件示例中,您将构建选择函数,如果它所关注的状态片段发生变化,这些函数只会重新计算状态。

可能的例子:

import { createSelector } from 'reselect'

const widgetByIdSelector = (state, props) => state.widgets[props.widgetId]
// this is the `input` function for you selector: as input we take the   
// specific slice of state a specific widgetId requests.
// the main idea is: only if the `input` of this function changes, it'll 'reselect' that state.

export const widgetSelector = createSelector(
   widgetByIdSelector,
    (widgetById) => { 
         return { widgetById } 
   }

@connect(widgetSelector)
export default class Widget extends Component { ... }

我不知道这段代码是否有效,是在互联网连接不稳定的火车上写的,但这是主要想法......

对于 reducer 和 action creators(你可能会做这样的事情):

export function createActionForSpecificWidgetById(widgetId, payload) {
    return {
       type: ACTIONS.HERE_COMES_YOUR_ACTION_TYPE,
       widgetId,
       payload
    }
}

function reducer(state = initialState, action) {
  switch(action.type) {
  case HERE_COMES_YOUR_ACTION_TYPE:
      //now you can modify the state of the specific widgetId because you have access to the id at action.widgetId
}

这就是您要找的吗?

关于javascript - 将嵌套的 Redux 智能组件与 reducer 连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728901/

有关javascript - 将嵌套的 Redux 智能组件与 reducer 连接起来的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  5. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  6. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  7. ruby-on-rails - 使用回形针的嵌套形式 - 2

    我有一个名为posts的模型,它有很多附件。附件模型使用回形针。我制作了一个用于创建附件的独立模型,效果很好,这是此处说明的View(https://github.com/thoughtbot/paperclip):@attachment,:html=>{:multipart=>true}do|form|%>posts中的嵌套表单如下所示:prohibitedthispostfrombeingsaved:@attachment,:html=>{:multipart=>true}do|at_form|%>附件记录已创建,但它是空的。文件未上传。同时,帖子已成功创建...有什么想法吗?

  8. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

  9. ruby - 如何根据长度将路径数组转换为嵌套数组或散列 - 2

    我需要根据字符串路径的长度将字符串路径数组转换为符号、哈希和数组的数组给定以下数组:array=["info","services","about/company","about/history/part1","about/history/part2"]我想生成以下输出,对不同级别进行分组,根据级别的结构混合使用符号和对象。产生以下输出:[:info,:services,about:[:company,history:[:part1,:part2]]]#altsyntax[:info,:services,{:about=>[:company,{:history=>[:part1,:pa

  10. ruby - 我的 Ruby IRC 机器人没有连接到 IRC 服务器。我究竟做错了什么? - 2

    require"socket"server="irc.rizon.net"port="6667"nick="RubyIRCBot"channel="#0x40"s=TCPSocket.open(server,port)s.print("USERTesting",0)s.print("NICK#{nick}",0)s.print("JOIN#{channel}",0)这个IRC机器人没有连接到IRC服务器,我做错了什么? 最佳答案 失败并显示此消息::irc.shakeababy.net461*USER:Notenoughparame

随机推荐