从这两个负责获取当前用户信息的处理程序开始:
(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))
在一个页面中,我想显示朋友列表,但问题是它取决于首先获取的用户:
Cordova
我应该如何构建此代码?
答案 0 :(得分:1)
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将首先存储检索到的用户并开始提取朋友。
答案 1 :(得分:0)
从article about solving the CPU hog problem获取一些灵感来自我使get-friends自己调用而用户为零但是为了避免向服务器发送许多请求,它还会添加一个关于被请求用户的标记:
(re-frame/register-handler
:get-friends
(fn [db [_ user-requested]]
(if-let [user (:user db)]
(ajax/GET (str "/users/" (get-in db [:user :id]))
{:handler #(re-frame/dispatch [:got-friends %1])})
(do
(when (not user-requested)
(re-frame/dispatch [:get-user]))
(re-frame/dispatch [:get-friends true])))
db))
它可以工作,但是在本地机器上,它设法自己调用9次左右,直到得到用户设置用户为止。不确定这是否是一个问题,如果存在,我会对其他解决方案持开放态度。