我知道Clojure是关于不可变数据的。所以,如果你有一个原子(比如值为0),改变它的值的方法是取消引用原子并使用交换!或重置! (现在说价值1)。但是,全局原子仍然具有值0并且在特定的重置中!或交换!功能它有价值1.(我相信这是正确的)。我的问题是,我可以使用另一个函数来更改原子的值,该值为1。
更清楚
(def table-data {:headers ["RIC-Code" "Isin" "Currency" "Description"]
:rows []})
(defonce fields (atom {}))
(defonce errors (atom nil))
(defonce isin (atom "test")
(defonce tdata (atom table-data))
(defn get-ric [ric isin]
(GET "/search-isin"
{:params {:ric ric}
:headers {"Accept" "application/transit+json"}
:handler #(do
(.log js/console (str "get-msg response : " %))
(reset! isin %)
(reset! tdata {:headers ["RIC-Code" "Isin" "Currency" "Description"]
:rows @isin}))}))
(defn replace-value [struct]
(walk/prewalk-replace {"id" "name"} struct))
(defn isin-form2 [isin]
[:div.content
[errors-component errors :server-error]
[:div.form-group
[errors-component errors :name]
[:p "Enter RIC-Code:"
[:input.form-control
{:type :text
:name :ric
:on-change #(swap! fields assoc :ric (-> % .-target .-value))
:value (:ric @fields)}]]
[errors-component errors :message]
[:input.btn.btn-primary
{:type :submit
:on-click #(do
(get-ric (:ric @fields) isin))
:value "Search RIC-Code"}]
[rt/reagent-table tdata]
[:input.btn.btn-primary
{:type :submit
:on-click #(do
(reset! tdata {:headers ["RIC-Code" "Isin" "Currency" "Description"]
:rows (swap! isin (replace-value %))}))
:value "Change"}]]])
上面代码的作用是在isin-form2中,它取一个初始值,然后插入到包含关键字ric的字段中。第一个按钮调用get-ric函数并返回tdata。 (在get-ric中,isin是一个原子,它是矢量的矢量,即[[“id”...] [...] ... [...]])我想要的第二个按钮是使用replace-value交换name的值id。但是当我尝试交换时,在第二个按钮! isin的价值没有改变
答案 0 :(得分:0)
您没有给swap!
一个功能。尝试:
(swap! isin #(replace-value %))
答案 1 :(得分:0)
也许这可以解释它是如何运作的:
(def my-state (atom 0))
(defn fn1 []
(newline)
(println :fn1-enter @my-state)
(swap! my-state inc)
(println :fn1-exit @my-state)
(newline))
(defn fn2 []
(newline)
(println :fn2-enter @my-state)
(swap! my-state inc)
(println :fn2-exit @my-state)
(newline))
(println :main-1 @my-state)
(fn1)
(println :main-2 @my-state)
(fn2)
(println :main-3 @my-state)
结果
:main-1 0
:fn1-enter 0
:fn1-exit 1
:main-2 1
:fn2-enter 1
:fn2-exit 2
:main-3 2
答案 2 :(得分:0)
我遇到了一个类似的问题,即原子没有跨不同的函数更改其值(即,该值将在一个位置更改,而我需要在另一位置更改该结果),所以我最终在全局范围内定义了原子。虽然这可能不是理想的解决方案,但我认为这种方法可以在没有问题的情况下起作用!