标签: hyperapp

通过引用更新树结构中的项并返回更新的树结构

我目前正在使用 HyperappJS (V2) 和 RamdaJS 学习函数式编程。我的第一个项目是一个简单的博客应用程序,用户可以在其中评论帖子或其他评论。评论表示为树结构。

我的状态看起来像这样:

// state.js
export default {
    posts: [
        {
            topic: `Topic A`, 
            comments: []
        },
        {
            topic: `Topic B`, 
            comments: [
                {
                    text: `Comment`, 
                    comments: [ /* ... */ ]
                }
            ]
        },
        {
            topic: `Topic C`, 
            comments: []
        }
    ],
    otherstuff: ...
}
Run Code Online (Sandbox Code Playgroud)

当用户想要添加评论时,我将当前树项传递给我的 addComment-action。在那里我将评论添加到引用的项目并返回一个新的状态对象以触发视图更新。

所以,目前我正在这样做并且它工作正常:

// actions.js
import {concat} from 'ramda'   
export default {
    addComment: (state, args) => {
        args.item.comments = concat(
            args.item.comments, 
            [{text: args.text, comments: []}]
        )
        return {...state}
    }
} …
Run Code Online (Sandbox Code Playgroud)

tree functional-programming ramda.js hyperapp

1
推荐指数
2
解决办法
387
查看次数

标签 统计

functional-programming ×1

hyperapp ×1

ramda.js ×1

tree ×1