审核中~
溜忙之道
首页
溜忙手册
offer之道
项目Git
写文章
登录
·
注册
登录
没有账号,去注册
注册
已有账号,去登录
博客
初识Redux中的Action, Reducer, Store
南易_站长
阅读量:12515
关注
初识Redux中的Action, Reducer, Store
# Store, Redux 和 Mobx * 前端数据流方案包括了 flux, redux 和 mobx. 在其中数据存储的地方, 就叫做 store. * Redux: * 参考[这里](https://www.jianshu.com/p/2d5d33dbfd0b) * Mobx * Mobx 是 flux 实现的后起之秀. 以更简单的时候和更少的概念, 让 flux 使用起来变得更简单. * 相比 Redux 有mutation, action, dispatch 等概念. mobx则更加简洁, 更符合对store 增删改查的操作概念. # Mobx 快速入门 通过下述的代码, 我们可以完成一个 react-mobx 实现的计数器. 点击[这里](https://codesandbox.io/s/lp557o286q)查看实际效果. ## 安装依赖项: mobx, mobx-react ```undefined npm i mobx mobx-react ``` ## 定义observable, observer 和 action * 定义一个状态对象, 它具有可观察的属性, 我们将它称为 **observable** * 首先我们需要定义一个状态对象 * 将其转化为可观察状态 * 将状态对象传递给 mobx observable() ```jsx import {observable} from 'mobx'; let appState = observable({ timer: 0 }); ``` * 创建一个react组件, 它能够响应 observable 的变化, 我们将它称为 observer * 创建一个 React 组件. * 将其转化为 响应 observable 的组件 * 使用 mobx-react observer() 来包裹它. ```jsx let App = observer(({ appState }) => { return (
Time passed: {appState.timer}
); }); ``` * 定义更改状态的函数, 我们将它称为 action * 创建一个函数来更改 observable. * 使用 mobx action来包裹它. ```jsx setInterval(action(()=>{ appState.timer +=1 }), 1000) ``` ## 完整代码 ```jsx import React from "react"; import ReactDOM from "react-dom"; import { observable, action } from "mobx"; import { observer } from "mobx-react"; // create State object let appState = observable({ timer: 0 }); // define action setInterval( action(() => { appState.timer += 1; }), 1000 ); appState.resetTimer = action(() => { appState.timer = 0; }); // create observer let App = observer(({ appState }) => { return (
Time passed : {appState.timer}
reset timer
); }); const root = document.getElementById("root"); ReactDOM.render(
, root); ``` ## 参考 [https://mobx.js.org/intro/overview.html](https://mobx.js.org/intro/overview.html)
评论
表情
发送
0
评论