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
配置。
添加導航鏈接 (Add navigation links)
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
componentsLink
組件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
組件,但是在某些情況下(例如重定向),直接設置視圖可能是不可避免的。 讓我們更新App
和TodoList
組件,以使用這兩種方法添加一些導航鏈接:
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