使用React和Redux,我可以从window
中获取一个初始状态对象(然后忽略它/删除它)。这对于加载当前用户或URL的资源标识符等概念非常有用,例如: :user_id
(而不是解析Redux中的URL以获取它们)。
如何以初始状态渲染我的Elm应用程序?
答案 0 :(得分:3)
您可以使用programWithFlags
功能传入数据来初始化您的Elm应用程序以启动应用程序。例如,使用用户ID初始化:
榆树:
module Main exposing (..)
import Html exposing (Html, div, h1, text)
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = (\_ -> Sub.none)
}
-- MODEL
type alias Model =
{ userId : Int
}
init : { userId : Int } -> ( Model, Cmd Msg )
init flags =
-- This is the key piece. You can use the passed in "flags"
-- record to build the initial state of your Model
( Model flags.userId, Cmd.none )
-- UPDATE
type Msg
= NoOp
update : Msg -> Model -> ( Model, Cmd Msg )
update NoOp model =
( model, Cmd.none )
-- VIEW
view : Model -> Html Msg
view model =
div [] [ h1 [] [ text ("User ID: " ++ toString model.userId) ] ]
HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="elm.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
// The flags get passed in here
Elm.Main.fullscreen({ userId: 42 });
</script>
</html>
答案 1 :(得分:2)
<!DOCTYPE HTML>
<html>
<head><meta charset="UTF-8"><title>Landing</title>
<link rel="stylesheet" type="text/css" href="/semantic.min.css">
<link rel="stylesheet" type="text/css" href="/styles.css">
<script src="https://code.jquery.com/jquery-3.1.0.slim.min.js" integrity="sha256-cRpWjoSOw5KcyIOaZNo4i6fZ9tKPhYYb6i5T9RSVJG8=" crossorigin="anonymous"></script>
<script src="/semantic.min.js"></script>
<script src="/elm.js"></script>
<script id="sample-data" type="application/json">
{{sample}}
</script>
<body>
<script>
var app = Elm.Main.fullscreen({
host: document.location.host,
protocol: document.location.protocol,
sample: document.getElementById("sample-data").innerHTML
});
</script>
</body>
</head>
</html>
榆树:
type alias Flags =
{ host : String
, protocol : String
, sample : Maybe String
}
init : Flags -> ( Model, Cmd Action )
init flags =
( { view =
case flags.sample of
Just string ->
SampleFleetViewModel <|
case Json.Decode.decodeString Codec.decodeFleetUpdates string of
Ok model ->
SampleFleetView.ActualModel model
Err error ->
SampleFleetView.Error error
Nothing ->
EnterFleetUrlModel EnterFleetUrl.init
, host = flags.host
, protocol = flags.protocol
}
, Cmd.none
)