gpt4 book ai didi

clojure - 如何让处理程序在重新框架中按顺序运行?

转载 作者:行者123 更新时间:2023-12-02 10:10:08 25 4
gpt4 key购买 nike

从这两个负责获取当前用户信息的处理程序开始:

(re-frame/register-handler
:got-user
(fn [db [_ user]]
(assoc db :user user)))

(re-frame/register-handler
:get-user
(fn [db [_]]
(ajax/GET "/user"
{:handler #(re-frame/dispatch [:got-user %1])})
db))

在一个页面中,我想显示好友列表,但问题是这取决于首先获取的用户:

(re-frame/register-handler
:get-friends
(fn [db [_]]
(when (nil? (:user db))
(re-frame/dispatch [:get-user]))
; Here's the problem, as I need to way for get-users and got-users to run.
(ajax/GET (str "/users/" (get-in db [:user :id]))
{:handler #(re-frame/dispatch [:got-friends %1])})
db))

我应该如何构建这段代码?

最佳答案

First, the documentation specifically warns against creating handlers with side-effects (即从事件处理程序调度事件)。其次,不要尝试重用事件处理程序,而是将可重用部分重构为辅助函数。使用re-frame-http-fx ,我会写这样的东西:

(reg-event-fx
:get-friends
[trim-v]
(fn
[{db :db} [_]]
{:http-xhrio (if (:user db)
{:method :get
:uri (str "/users/" (get-in db [:user :id]))
:on-success [:got-friends]
:on-failure [:get-friends-load-failed]}

{:method :get
:uri "/user"
:on-success [:get-friends-for-user]
:on-failure [:get-friends-user-load-failed]})
:db db}
))

:get-friends-for-user 然后将首先存储检索到的用户并开始获取好友。

关于clojure - 如何让处理程序在重新框架中按顺序运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31985649/

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