Redux 入门
1.什么是Redux管理Web应用全局状态的框架。 单页面应用,顾名思义,和传统项目的最明显区别就是项目只有一个页面,页面有一个根元素,我们写的每一个页面是一个大的组件,前端接管路由来渲染不同的页面组件。 随着应用的复杂,前端需要存储更多的state,包括缓存的全局数据,本地生成尚未持久化到服务器的数据,也包括 UI 状态,如激活的路由,被选中的标签,是否显示加载动效或者分页器等等。 如果是单纯的数据缓存 也没什么需要考虑的东西,放到内存就可以了, 重点是还要让state和view有绑定的关系。state的变化能够触发view的变化。 在我们的项目中,没有用redux之前,我们都是页面组件管理state,出现以下需求的时候,写起来就比较复杂
2.Redux的原则和设计思想2.1 三大原则
不得改写参数 2.2 设计思想:(1)Web 应用是一个状态机,视图与状态是一一对应的。 (2)所有的状态,保存在一个对象里面。 3.Redux中的概念3.1 Action执行的动作,包括动作所需要的数据,改变store数据的唯一来源,一般是通过store.dispatch() 将 action 传到 store。 Action 本质上是 JavaScript 普通对象。 flux-standard-action FSA标准
3.2 Reducer根据action 做更新state的操作。 Action 只是描述了有事情发生了这一事实,并没有指明应用如何更新 state。而这正是 reducer 要做的事情。 3.3 StoreStore就是保存全局state的容器,保存三个常用的api
3.4 单项数据流用户通过View,dispatch 相应的action,store调用reducer获取最新的state,并触发通过subscribe订阅的监听函数,监听函数中我们通过store的getState方法获取最新的state,更新view。 4.应用实例simpleredux/index.js import {createStore} from 'redux'; export function createAction(type,payload) { return { type,payload } } const initialState = { time: new Date().getTime() } function reducer(state = initialState,action) { switch (action.type) { case 'NOW_TIME': return { ...state,time: action.payload } default: return state; } } let store; export function getStore() { if(store) return store; return store = createStore(reducer); } TestRedux.js 'use strict'; import React,{ Component } from 'react'; import { StyleSheet,View,Text } from 'react-native'; import MtButton from '@scfe/react-native-button'; import {getStore,createAction} from '../../simpleredux/index'; const store = getStore(); class TestRedux extends Component { constructor(props) { super(props); let state = store.getState(); this.state = { time: state.time }; store.subscribe(()=>{ let state = store.getState(); this.setState({ time: state.time }); }); } _sendAction() { let action = createAction('NOW_TIME',new Date().getTime()); store.dispatch(action); } render() { return ( <View style={styles.container}> <Text>{this.state.time} </Text> <MtButton text="发出action" onPress={this._sendAction.bind(this)} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1,padding: 40 } }); export default TestRedux; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |