react 使用 mobx_如何使用React和MobX狀態樹構建基于狀態的路由器

react 使用 mobx

by Miles Till

由Miles Till

如何使用React和MobX狀態樹構建基于狀態的路由器 (How to build a state-based router using React and MobX State Tree)

Introducing mobx-state-tree-router

Mobx狀態樹路由器簡介

If you want to skip ahead to the finished example you can check it out at mobx-state-tree-router-demo.

如果您想跳至完成的示例,可以在mobx-state-tree-router-demo上進行檢查 。

I wrote a library that makes it easy to configure state-based routing in MobX State Tree powered React apps, and I want to share it with you. To do this I will demonstrate how to build a very simple Todo app.

我寫了一個庫,使在MobX狀態樹驅動的React應用程序中配置基于狀態的路由變得容易,我想與您共享它。 為此,我將演示如何構建一個非常簡單的Todo應用程序。

Michel Weststrate, the creator of MobX, wrote a great article titled How to decouple state and UI (a.k.a. you don’t need componentWillMount). I recommend reading it to understand the philosophy that inspired me to write mobx-state-tree-router. The key idea is that the application UI should be a function of the state.

MobX的創建者Michel Weststrate寫了一篇很棒的文章,標題為《 如何使狀態與UI分離》(又稱您不需要componentWillMount) 。 我建議閱讀它以了解啟發我編寫mobx-state-tree-router的哲學。 關鍵思想是應用程序UI應該是狀態的函數。

“This approach has better decoupling of state and UI. This has a few advantages:
“這種方法可以更好地將狀態與UI分離。 這有一些優點:
1. The complete application flow can be tested without ever needing to instantiate a component.
1.無需實例化組件即可測試完整的應用程序流程。
2. More components can be dumb; they don’t have to fetch data or process routing.
2.可以使更多組件變得笨拙; 他們不必獲取數據或處理路由。
3. Our stores become more like a state machine, making it easy to follow the transitions of our application.”
3.我們的商店變得更像一臺狀態機,可以輕松地跟蹤我們的應用程序的過渡。”
- Michel Weststrate
-米歇爾·韋斯特斯特

先決條件 (Prerequisites)

These will need to be installed to follow this tutorial:

必須安裝這些程序才能遵循本教程:

  • Node.js — used for running the dev server

    Node.js-用于運行開發服務器

  • Yarn — used for package management

    紗線 -用于包裝管理

Note: NPM can be used instead of Yarn but some commands may be different.

注意:可以使用NPM代替Yarn,但是某些命令可能有所不同。

創建一個基本的React應用 (Create a basic React app)

使用create-react-app快速入門 (Use create-react-app to get started quickly)

If you haven’t used it before, the easiest way to get started with a React app is to use a scaffolding tool by the developers of React called Create React App. This tool configures Webpack and Babel for you with the most common requirements met.

如果您以前從未使用過它,那么最開始使用React應用程序的最簡單方法是使用React開發人員的腳手架工具,稱為創建React App 。 該工具為您配置Webpack和Babel ,使其滿足最常見的要求。

In your terminal run the following commands:

在您的終端中運行以下命令:

npx create-react-app state-router-democd state-router-demoyarn start

You will now have a fully functioning basic React app to play with.

現在您將擁有一個功能齊全的基本React應用程序。

刪除此示例不需要的create-react-app內容 (Remove create-react-app stuff not needed for this example)

For the purposes of this tutorial we don’t need a lot of the stuff that create-react-app generates so go ahead and delete:

就本教程而言,我們不需要大量create-react-app生成的東西,因此請繼續刪除:

src/App.csssrc/App.test.jssrc/index.csssrc/logo.svgsrc/serviceWorker.js

Note: Feel free to keep the css files and add your own styling.

注意:隨時保留css文件并添加自己的樣式。

To keep things organised, create a components directory in our src and move src/App.js to src/components/App.js.

為了使事情井井有條,請在src創建一個components目錄,然后將src/App.js移至src/components/App.js

Now update the following files to remove references to the files we deleted:

現在更新以下文件,以刪除對我們刪除的文件的引用:

src/components/App.js

src / components / App.js

src/index.js

src / index.js

If you still have the app running you will notice your browser has updated to show you the following:

如果您仍在運行該應用程序,則會注意到您的瀏覽器已更新,可以顯示以下內容:

創建一個主頁組件 (Create a Home page component)

In the components directory, create a file for our Home page component:

components目錄中,為我們的主頁組件創建一個文件:

src/components/Home.js

src / components / Home.js

Update the App component to render our new Home page component:

更新App組件以呈現我們的新Homepage組件:

src/components/App.js

src / components / App.js

添加MobX狀態樹模型 (Add MobX State Tree models)

安裝MobX和MobX狀態樹 (Install MobX and MobX State Tree)

MobX is a library for state management, and it works great with React as our renderer. MobX State Tree is a tree shaped state container built on top of MobX.

MobX是用于狀態管理的庫,與React作為我們的渲染器一起使用時效果很好。 MobX狀態樹是建立在MobX之上的樹狀狀態容器。

In your terminal run:

在您的終端運行中:

yarn add mobx mobx-react mobx-state-tree

Like our we did for our components, create a models directory to keep our MobX State Tree models organised.

就像我們對組件所做的一樣,創建一個models目錄以保持我們的MobX狀態樹模型井井有條。

創建一個RootStore模型 (Create a RootStore model)

In our state tree we’ll have a RootStore which holds our data stores (in this case a TodoStore) and our RouterStore, but we’ll get to that later.

在我們的狀態樹中,我們將有一個RootStore來保存我們的數據存儲(在本例中為TodoStore )和我們的RouterStore ,但是我們稍后RouterStore

src/models/RootStore.js

src / models / RootStore.js

創建TodoStore和Todo模型 (Create TodoStore and Todo models)

Our TodoStore contains Todo objects which are able to be created, removed, and updated. We also need to be able to find a Todo object by its id.

我們的TodoStore包含可以創建,刪除和更新的Todo對象。 我們還需要能夠通過其id查找Todo對象。

src/models/TodoStore.js

src / models / TodoStore.js

初始化RootStore (Initialize the RootStore)

When our app loads, we want to initialize the RootStore with a known state. For this trivial example we won’t be concerned about persisting our data to storage in any way. We then want to make sure the RootStore is available to be injected into our components, so we use the MobX React component Provider to do this.

應用加載時,我們想用已知狀態初始化RootStore 。 對于這個簡單的示例,我們將不關心以任何方式將數據持久存儲到存儲中。 然后,我們要確保可以將RootStore注入到我們的組件中,因此我們使用MobX React組件Provider來執行此操作。

src/index.js

src / index.js

創建一個TodoList頁面組件 (Create a TodoList page component)

Now that we have a RootStore for our state tree, we need some components to view and change the data.

現在,我們為狀態樹提供了一個RootStore ,我們需要一些組件來查看和更改數據。

src/components/TodoList.js

src / components / TodoList.js

Update the App component to display our new TodoList component.

更新App組件以顯示我們的新TodoList組件。

src/components/App.js

src / components / App.js

At this point the app should have a list of Todo objects which you can add to and remove from.

此時,該應用程序應具有您可以添加和刪除的Todo對象的列表。

創建一個Todo頁面組件 (Create a Todo page component)

Now we want to create a new component to display and edit a Todo object. Note that we are using inject to make the RootStore available in the component’s props.

現在,我們要創建一個新組件以顯示和編輯Todo對象。 請注意,我們正在使用inject使RootStore在組件的props中可用。

src/components/Todo.js

src / components / Todo.js

Update the App component to display our new Todo component.

更新App組件以顯示我們的新Todo組件。

Now our updated app allows us to edit the data of the Todo whose id we pass to the Todo page component in <Todo todoId={0} />.

現在,我們更新的應用程序允許我們編輯Todo的數據,該ID的ID傳遞到<Todo todoId={0} />中的Todo頁面組件。

添加基于狀態的路由 (Add state-based routing)

At this point we should have a React app with our data stored in a MobX State Tree container. The data container is then being injected into the components that need access to the data. Now we want to connect together our page components in our app. A common approach would be to use a component based router such as React Router. Often the components become cluttered with route definitions and mount event handlers. This doesn’t suit our state-first philosophy.

此時,我們應該有一個React應用,其數據存儲在MobX狀態樹容器中。 然后將數據容器注入需要訪問數據的組件中。 現在,我們要將應用程序中的頁面組件連接在一起。 一種常見的方法是使用基于組件的路由器,例如React Router 。 通常,組件會因路由定義和安裝事件處理程序而變得混亂不堪。 這不符合我們的國家優先理念。

I will now show you how to add mobx-state-tree-router to your app.

現在,我將向您展示如何向您的應用添加mobx-state-tree-router。

安裝mobx-state-tree-router (Install mobx-state-tree-router)

In your terminal run:

在您的終端運行中:

yarn add mobx-state-tree-router

將路由器添加到RootStore (Add the router to the RootStore)

src/models/RootStore.js

src / models / RootStore.js

創建視圖 (Create views)

The router needs to be configured with a map of view models which define the route paths to match against and the page components to display. Hooks into the page change cycle can be defined on a view to perform data fetching, route change cancelling, redirection, and other tasks. These hooks can be synchronous or asynchronous.

路由器需要配置一個視圖模型圖,以定義要匹配的路由路徑以及要顯示的頁面組件。 可以在視圖上定義頁面更改周期的掛鉤,以執行數據獲取,路由更改取消,重定向和其他任務。 這些掛鉤可以是同步的或異步的。

These hooks are:

這些掛鉤是:

  • beforeExit(self, params)

    beforeExit(self, params)

  • beforeEnter(self, params)

    beforeEnter(self, params)

  • onExit(self, params)

    onExit(self, params)

  • onEnter(self, params)

    onEnter(self, params)

If either of the before hooks return false the route change will be cancelled.

如果任何一個前鉤返回false則路由更改將被取消。

Create a views file:

創建一個views文件:

src/views.js

src / views.js

啟動我們的應用程序時初始化路由器 (Initialize the router when our app starts)

The router can be started by calling startRouter(router). This function connects the router to the browser’s history and configures the routing based on router’s views.

可以通過調用startRouter(router)來啟動startRouter(router) 。 此功能將路由器連接到瀏覽器的歷史記錄,并根據路由器的視圖配置路由。

src/index.js

src / index.js

渲染StateRouter (Render the StateRouter)

Update the App component to include the StateRouter component, which renders the appropriate component for the router’s current view.

更新App組件以包括StateRouter組件,該組件將為路由器的當前視圖呈現適當的組件。

src/components/App.js

src / components / App.js

Now our app will respond to changes in the url path, for example /todos will show our TodoList component and /todos/0 will show our Todo component as configured in views.js.

現在,我們的應用程序將響應url路徑中的更改,例如/todos將顯示我們的TodoList組件, /todos/0將顯示我們的Todo組件,它們在views.js配置。

Currently our app doesn’t have any way to navigate around other than changing the url directly. This doesn’t work particularly well in this simple example as the data in our RootStore will get reset to the initial state as defined in index.js every time the page loads.

目前,除了直接更改網址外,我們的應用程序沒有其他導航方式。 在這個簡單的示例中,這并不是特別有效,因為每次頁面加載時, RootStore的數據都會重置為index.js定義的初始狀態。

There are 2 other ways to change the route using mobx-state-tree-router:

還有另外兩種使用mobx-state-tree-router更改路由的方法:

  • Link components

    Link組件

  • Calling router.setView(view, params) directly

    直接調用router.setView(view, params)

I recommend using Link components where possible, but in some cases (like redirects) setting the view directly may be unavoidable. Let’s update our App and TodoList components to add some navigation links using both methods:

我建議盡可能使用Link組件,但是在某些情況下(例如重定向),直接設置視圖可能是不可避免的。 讓我們更新AppTodoList組件,以使用這兩種方法添加一些導航鏈接:

src/components/App.js

src / components / App.js

src/components/TodoList.js

src / components / TodoList.js

You will now be able to add a Todo item on the todos view, then click the open button to go the todo view for the new item:

現在,您就可以添加一個Todo的項目todos視圖,然后單擊打開按鈕去todo視圖新項目:

結論 (Conclusion)

I created mobx-state-tree-router because I found that there was a gap in the landscape for a state-based routing library to use with MobX State Tree. I have found it to be useful for me, so I hope it can also be useful to the wider community.

我創建了mobx-state-tree-router,是因為發現在景觀中存在一個空白狀態,無法將基于狀態的路由庫與MobX狀態樹一起使用。 我發現它對我有用,因此我希望它對更廣泛的社區也有用。

If you haven’t already please read Michel Weststrate’s article for some background on state-based routing.

如果您還沒有,請閱讀Michel Weststrate的文章,以獲取有關基于狀態的路由的一些背景知識。

If you have any issues to raise or contributions to make, please head over to mobx-state-tree-router on Github.

如果您有任何問題需要籌集或作出貢獻,請前往Github上的mobx-state-tree-router 。

翻譯自: https://www.freecodecamp.org/news/how-to-build-a-state-based-router-using-react-and-mobx-state-tree-e91b2b8e8d79/

react 使用 mobx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391842.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391842.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391842.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

docker在Centos上的安裝

Centos6安裝docker 系統&#xff1a;centos6.5 內核&#xff1a;3.10.107-1(已升級)&#xff0c;docker對RHEL/Centos的最低內核支持是2.6.32-431&#xff0c;epel源的docker版本推薦內核為3.10版本。 內核升級可參考&#xff1a;https://www.jslink.org/linux/centos-kernel-u…

Lambda表達式的前世今生

Lambda 表達式 早在 C# 1.0 時&#xff0c;C#中就引入了委托&#xff08;delegate&#xff09;類型的概念。通過使用這個類型&#xff0c;我們可以將函數作為參數進行傳遞。在某種意義上&#xff0c;委托可理解為一種托管的強類型的函數指針。 通常情況下&#xff0c;使用委托來…

matplotlib柱狀圖、面積圖、直方圖、散點圖、極坐標圖、箱型圖

一、柱狀圖 1.通過obj.plot() 柱狀圖用bar表示&#xff0c;可通過obj.plot(kindbar)或者obj.plot.bar()生成&#xff1b;在柱狀圖中添加參數stackedTrue&#xff0c;會形成堆疊圖。 fig,axes plt.subplots(2,2,figsize(10,6)) s pd.Series(np.random.randint(0,10,15),index …

微信支付商業版 結算周期_了解商業周期

微信支付商業版 結算周期Economics is an inexact science, finance and investing even more so (some would call them art). But if there’s one thing in economics that you can consistently count on over the long run, it’s the tendency of things to mean revert …

leetcode 448. 找到所有數組中消失的數字

給定一個范圍在 1 ≤ a[i] ≤ n ( n 數組大小 ) 的 整型數組&#xff0c;數組中的元素一些出現了兩次&#xff0c;另一些只出現一次。 找到所有在 [1, n] 范圍之間沒有出現在數組中的數字。 您能在不使用額外空間且時間復雜度為O(n)的情況下完成這個任務嗎? 你可以假定返回…

前端初學者開發學習視頻_初學者學習前端開發的實用指南

前端初學者開發學習視頻by Nikita Rudenko通過尼基塔魯登科(Nikita Rudenko) 初學者學習前端開發的實用指南 (A practical guide to learning front end development for beginners) I started my coding journey in spring 2018, a bit less than one year ago. I earned som…

weblogic啟動失敗案例(root啟動引起的權限問題)

weblogic的一個domain啟動失敗&#xff0c;在日志中有如下信息提示&#xff1a; **************************************************** To start WebLogic Server, use a username and ** password assigned to an admin-level user. For ** server administration, us…

HTTP請求示例

HTTP請求格式當瀏覽器向Web服務器發出請求時&#xff0c;它向服務器傳遞了一個數據塊&#xff0c;也就是請求信息&#xff0c;HTTP請求信息由3部分組成&#xff1a;l 請求方法URI協議/版本l 請求頭(Request Header)l 請求正文下面是一個HTTP請求的例子&#xff1a;GET/sa…

Bootstrap——可拖動模態框(Model)

還是上一個小項目&#xff0c;o(╥﹏╥)o&#xff0c;要實現點擊一個div或者button或者一個東西然后可以彈出一個浮在最上面的彈框。網上找了找&#xff0c;發現Bootstrap的Model彈出框可以實現該功能&#xff0c;因此學習了一下&#xff0c;實現了基本彈框功能&#xff08;可拖…

mfcc中的fft操作_簡化音頻數據:FFT,STFT和MFCC

mfcc中的fft操作What we should know about sound. Sound is produced when there’s an object that vibrates and those vibrations determine the oscillation of air molecules which creates an alternation of air pressure and this high pressure alternated with low …

leetcode 765. 情侶牽手(并查集)

N 對情侶坐在連續排列的 2N 個座位上&#xff0c;想要牽到對方的手。 計算最少交換座位的次數&#xff0c;以便每對情侶可以并肩坐在一起。 一次交換可選擇任意兩人&#xff0c;讓他們站起來交換座位。 人和座位用 0 到 2N-1 的整數表示&#xff0c;情侶們按順序編號&#xff…

ariel字體_播客第58集:軟件開發人員和freeCodeCamp超級巨星Ariel Leslie

ariel字體On this weeks episode of the freeCodeCamp.org podcast, Abbey interviews Ariel Leslie, a software developer and avid contributor to the freeCodeCamp community.在本周的freeCodeCamp.org播客節目中&#xff0c;Abbey采訪了Ariel Leslie&#xff0c;他是free…

PHP繪制3D圖形

PEAR提供了Image_3D Package來創建3D圖像。圖像或光線在3D空間中按照X、Y 、Z 坐標定位。生成的圖像將呈現在2D空間中&#xff0c;可以存儲為 PNG、SVG 格式&#xff0c;或輸出到Shell。通過Image_3D可以很方便生成一些簡單的3D對象&#xff0c;例如立方體、錐體、球體、文本和…

清除日志的sql

SET NOCOUNT ONDECLARE LogicalFileName sysname,MaxMinutes INT,NewSize INTUSE cms -- 要操作的數據庫名SELECT LogicalFileName cms_log, -- 日志文件名MaxMinutes 10, -- Limit on time allowed to wrap log.NewSize 100 -- 你想設定的日志文件的大小(M)-- Setup / init…

r語言怎么以第二列繪制線圖_用衛星圖像繪制世界海岸線圖-第二部分

r語言怎么以第二列繪制線圖Part I of this blog series is here.本博客系列的第一部分 在這里 。 At the UKHO we are interested in the oceans, the seabed and the coastline — not to mention everything in and on them! In our previous blog, we (the UKHO Data Scien…

javascript創建類_如何在10分鐘內使用JavaScript創建費用管理器

javascript創建類by Per Harald Borgen通過Per Harald Borgen 如何在10分鐘內使用JavaScript創建費用管理器 (How to create an expense organizer with JavaScript in 10 minutes) 讓我們使用ES6和Dropbox API來防止收據變得混亂。 (Let’s use ES6 and the Dropbox API to k…

豆瓣API

Api V2 索引 圖書Api V2 電影Api V2 音樂Api V2 同城Api V2 廣播Api V2 用戶Api V2 日記Api V2 相冊Api V2 線上活動Api V2 論壇Api V2 回復Api V2 我去Api V2 https://developers.douban.com/wiki/?titleapi_v2 搜索圖書 GET https://api.douban.com/v2/book/search參數意義…

leetcode 485. 最大連續1的個數

給定一個二進制數組&#xff0c; 計算其中最大連續1的個數。 示例 1: 輸入: [1,1,0,1,1,1] 輸出: 3 解釋: 開頭的兩位和最后的三位都是連續1&#xff0c;所以最大連續1的個數是 3. 解題思路 遇到0時&#xff0c;將連續1的長度歸零。遇到1時&#xff0c;累加進長度 代碼 c…

HDU Today

經過錦囊相助&#xff0c;海東集團終于度過了危機&#xff0c;從此&#xff0c;HDU的發展就一直順風順水&#xff0c;到了2050年&#xff0c;集團已經相當規模了&#xff0c;據說進入了錢江肉絲經濟開發區500強。這時候&#xff0c;XHD夫婦也退居了二線&#xff0c;并在風景秀美…

JSP基礎--動作標簽

JSP基礎--動作標簽 JSP動作標簽 1 JSP動作標簽概述 動作標簽的作用是用來簡化Java腳本的&#xff01; JSP動作標簽是JavaWeb內置的動作標簽&#xff0c;它們是已經定義好的動作標簽&#xff0c;我們可以拿來直接使用。 如果JSP動作標簽不夠用時&#xff0c;還可以使用自定義標…