Elm Http请求初始化 [英] Elm Http Request on Init

查看:64
本文介绍了Elm Http请求初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Elm来说还很陌生,但逐渐熟悉它。我正在做一些简单的Http请求,这些请求在各个方面都成功(我可以显示数据,等等。)

I'm pretty new to Elm, but slowly getting familiar with it. I'm doing some simple Http Requests, which are successful in every aspect (I get the data to display, etc.)

目前,我只能获取fetchData触发onClick时,我想在init上初始化它,但是我无法解决这个问题。

For the moment I can only get my fetchData to trigger onClick, I would like to initialize this on init, but I'm having trouble wrapping my head around this.

....这是我的fetchData函数:

....here is my fetchData function:

fetchData : Cmd Msg
fetchData =
  Http.get repoInfoListDecoder "http://example/api"
    |> Task.mapError toString
    |> Task.perform ErrorOccurred DataFetched

当前在视图中由onClick事件触发的

Which is currently trigger in the view by a onClick event:

.....
, button [ onClick FetchData ] [ text "Load Data" ]
.....

我想避免通过按钮请求数据,而是希望在加载数据时应用已初始化。这是我的初始化:

I want to avoid requesting the data by a button, instead I want the data to load when the app is initialized. Here is my init:

init =
  let
    model =
      { message = "Welcome", repos = [] }
  in
    model ! []

我的更新(例如,被剥夺的物品……):

And my update (kind of stripped...for example's sakes):

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    NoOp ->
      model ! []
    ...........
    FetchData ->
      { model | message="hi" } ! [fetchData]
    ...........
    DataFetched repos ->
      { model | repos = repos, message = "The data has been fetched!" } ! []

这有意义吗?我在加载应用程序时初始化fetchData时遇到了困难,因此无需单击按钮即可获取数据即可显示我的数据。

Does this makes sense? I'm just having difficulty initializing fetchData when the app loads, so I can display my data without having to hit a button to fetch it.

谢谢!

推荐答案

使用 Html.program ,您的 init 函数返回要执行的模型和命令的初始数据。

When you use Html.program, your init function returns the initial data for your Model and Command to be executed.

命令是副作用,例如HTTP请求。

Commands are side-effects, like HTTP requests.

尝试更改 init 使其立即运行命令:

Try changing init so it runs a Command right away:

init: (Model, Cmd Msg)
init =
  let
    model =
      { message = "Welcome", repos = [] }
  in
    model ! [ fetchData ]

这篇关于Elm Http请求初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆