随着 JavaScript 单页应用开发日趋复杂,JavaScript 需要管理比任何时候都要多的 state (状态),管理这些状态也变得日趋复杂。redux就是一个 用于管理js应用状态的容器,它遵循下面三大原则:
1.单一数据源
整个应用的state被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个store中。
2.State 是只读的
惟一改变 state 的方法就是触发action,action 是一个用于描述已发生事件的普通对象。
3.使用纯函数来执行修改
为了描述 action 如何改变 state tree ,你需要编写reducers。
下面给出一个简单的例子帮助理解
'use strict'; import React,{ Component,PropTypes} from 'react'; import { StyleSheet, Text, View, Image, Button, AppRegistry, TouchableHighlight } from 'react-native'; import { createStore } from 'redux'; /* * auth:andy */ class Counter extends Component { static propTypes = { value: PropTypes.number.isRequired, onIncrement: PropTypes.func.isRequired, onDecrement: PropTypes.func.isRequired, } render() { const { value,onIncrement,onDecrement } = this.props console.log(value); //view return ( <View style={{ alignItems: 'center',}}> <TouchableHighlight onPress={onIncrement}> <Text style={{ fontSize: 20,margin:5}}>Tap me to ++</Text> </TouchableHighlight> <TouchableHighlight onPress={onDecrement}> <Text style={{ fontSize: 20,margin:5 }}>Tap me to -- </Text> </TouchableHighlight> <View style={styles.numberContainer}> <Text style={styles.number} >{value}</Text> </View> </View> ); } } //reducer函数,state默认值是0 function counter(state = 0,action) { //根据传进来的action改变state的值 switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } //传入reducer函数创建store const store = createStore(counter); export default class movie_redux extends Component { constructor(props) { super(props) this.state = { value: 0, } } componentDidMount = () => { //设置监听,当store的state值更新,刷新render store.subscribe(() => this.setState({ value: store.getState() })); } render() { return (<Counter value={this.state.value} onIncrement={() => store.dispatch({ type: 'INCREMENT' }) } onDecrement={() => store.dispatch({ type: 'DECREMENT' }) } /> ); } } const styles = StyleSheet.create({ numberContainer: { height: 150, justifyContent: 'center', alignItems: 'center', }, number: { fontSize: 36, color:'deeppink', }); AppRegistry.registerComponent('movie_redux',() => movie_redux);
更多redux的参考文章
Redux 中文文档
浅谈 React,Flux 与 Redux
近期 React-Native With Redux 开发的一点心得
在react-native中使用redux (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|