一步一步学习 ReactNative + Redux(2)
来源:互联网 发布:汤尼伯爵男装淘宝 编辑:程序博客网 时间:2024/06/06 02:18
写在开始
上篇中,我们搭建了 ReactNative + Redux 的结构、显示了初始数据。http://www.jianshu.com/p/adf8886f5408
这篇,我们需要做状态更改了,即 dispatch(action)
。
源码:https://github.com/eylu/web-lib/tree/master/ReactReduxDemo/app_step2
开发
这里,我们的任务如下:
- 给 TODO 项添加点击事件,点击后,切换 TODO 的状态(
status:true|false
) ; - 新建一个组件
TodoForm.component
,可以添加新的 TODO 项。
TODO 状态切换
1、使用 TouchableOpacity
这里我们只是给子组件 TodoListComponent
添加了点击事件,没有什么特别之处。
ReactReduxDemo/app/components/todo-list.component.js
文件,做如下修改:
import React, { Component } from 'react';import { Text, View, StyleSheet, TouchableOpacity, // 引入 TouchableOpacity} from 'react-native';export default class TodoListComponent extends Component{ constructor(props){ super(props); } toggleTodo(index){ // 点击事件,通过 props.method 调用容器组件的方法 this.props.toggleTodo && this.props.toggleTodo(index); } render(){ return ( <View style={styles.wrapper}> {this.props.todoList.map((todo, index)=>{ var finishStyle = {textDecorationLine:'line-through', color:'gray'}; return ( <TouchableOpacity onPress={()=>{this.toggleTodo(index)}}> // 这里使用了 TouchableOpacity,并添加了点击事件(注释会报错,请删除注释) <Text style={[styles.todo,todo.status&&finishStyle]}>{todo.title}</Text> </TouchableOpacity> ); })} </View> ); }}const styles = StyleSheet.create({ wrapper: { paddingHorizontal: 20, }, todo: { paddingVertical: 5, },});
2、使用 dispatch
子组件 TodoListComponent
的点击事件已完成,通过 props 调用容器组件的方法。容器组件 HomeContainer
调用 dispatch(action)
。
ReactReduxDemo/app/container/home.container.js
文件,做如下修改:
import React, { Component } from 'react';import { View, Text} from 'react-native';import { connect } from 'react-redux';import { changeTodoStatus } from '../actions/index'; // 引入 action import TodoListComponent from '../components/todo-list.component';class HomeContainer extends Component{ constructor(props){ super(props); } toggleTodo(index){ let { dispatch } = this.props; // 从 props 里解构出 dispatch dispatch(changeTodoStatus(index)); // 执行 dispatch(action) } render(){ return ( <View> <TodoListComponent todoList={this.props.todoList} toggleTodo={(index)=>{this.toggleTodo(index)}} /> // 这里添加了新 props toggleTodo (注释会报错,请删除注释) </View> ); }}// 基于全局 state ,哪些 state 是我们想注入的 propsfunction mapStateToProps(state){ return { todoList: state.todos, }}export default connect(mapStateToProps)(HomeContainer);
3、创建 action
这里,我们使用方法创建 action ,并将 action 的 type 字段全部使用常量(不直接使用字符串,方便统一管理与多处引用)
新建文件 ReactReduxDemo/app/actions/index.js
,如下:
/*********************************** action 类型常量 *************************************//** * 更改 TODO 状态 * @type {String} */export const TOGGLE_TODO_STATUS = 'TOGGLE_TODO_STATUS';/*********************************** action 创建函数 *************************************//** * 更改 TODO 状态 * @param {Number} index TODO索引 * @return {Object} action */export function changeTodoStatus(index){ return {type: TOGGLE_TODO_STATUS, index};}
4、使用 reducer 更新 state
还没完,我们创建了action
,并且派发了action
。但是,还没有响应action
。我们需要用reducer
响应action
,并返回新的state
。
ReactReduxDemo/app/reducers/index.js
,修改如下:
import { combineReducers } from 'redux';import { TOGGLE_TODO_STATUS } from '../actions/index'; // 引入 action ,使用 action 类型常量function todoList(state=[], action){ switch(action.type){ // 匹配响应 action,创建并返回新的 state (注意,不能修改state) case TOGGLE_TODO_STATUS: var todo = state[action.index]; return [ ...state.slice(0, action.index), Object.assign({}, todo, { status: !todo.status }), ...state.slice(action.index + 1) ]; default : // 在没有匹配到 action 时,返回原始state return state; }}const reducers = combineReducers({ todos: todoList});export default reducers;
好了,到现在为止,我们已经将 ReactNative 与 Redux 连接了起来,并响应了点击事件。
运行项目,点击 TODO 项,看看是否可以状态切换了呢。
添加新 TODO 项
到现在,如果对 Redux
还不太熟悉,没关系。
接下来,我们再来梳理与巩固一下 Redux 工作流。
1、新建子组件 TodoFormComponent
它有一个输入框、一个按钮,输入过程中,将输入对文字存入自己的 state
,点击按钮,调用 props
的父组件(容器组件)方法。
新建文件 ReactReduxDemo/app/components/todo-form.component.js
, 如下:
import React, { Component } from 'react';import { View, TextInput, Button, StyleSheet,} from 'react-native';export default class TodoFormComponent extends Component{ constructor(props){ super(props); this.state = { todo: null, }; } addTodo(){ this.props.addTodo && this.props.addTodo(this.state.todo); // 调用父组件方法 } setTodo(text){ this.setState({ todo: text }); } render(){ return ( <View style={styles.wrapper}> <TextInput style={styles.input} onChangeText={(text)=>{this.setTodo(text)}} /> <Button title="添加" onPress={()=>this.addTodo()} /> </View> ); }}const styles = StyleSheet.create({ wrapper: { paddingHorizontal: 10, flexDirection: 'row', }, input: { height: 30, borderColor: 'gray', borderWidth: 1, flex: 1, },});
没有什么特别,只是一个 React 组件。
2、使用 dispatch
容器组件HomeContainer
引入子组件,并定义添加新 TODO 项的方法,执行 dispatch
ReactReduxDemo/app/container/home.container.js
文件,修改如下:
import React, { Component } from 'react';import { View, Text} from 'react-native';import { connect } from 'react-redux';import { changeTodoStatus, addNewTodo } from '../actions/index'; // 引入新 actionimport TodoFormComponent from '../components/todo-form.component'; // 引入组件import TodoListComponent from '../components/todo-list.component';class HomeContainer extends Component{ constructor(props){ super(props); } addTodo(text){ let { dispatch } = this.props; // 从 props 里解构出 dispatch dispatch(addNewTodo(text)); // 执行 dispatch(action) } toggleTodo(index){ let { dispatch } = this.props; dispatch(changeTodoStatus(index)); } render(){ return ( <View> <TodoFormComponent addTodo={(text)=>{this.addTodo(text)}}/> // 渲染组件(注释会报错,请删除注释) <TodoListComponent todoList={this.props.todoList} toggleTodo={(index)=>{this.toggleTodo(index)}} /> </View> ); }}// 基于全局 state ,哪些 state 是我们想注入的 propsfunction mapStateToProps(state){ return { todoList: state.todos, }}export default connect(mapStateToProps)(HomeContainer);
3、定义 action
容器组件HomeContainer
中 dispatch 了新的 action,我们需要进行定义。
ReactReduxDemo/app/actions/index.js
文件,修改如下:
/*********************************** action 类型常量 *************************************//** * 更改 TODO 状态 * @type {String} */export const TOGGLE_TODO_STATUS = 'TOGGLE_TODO_STATUS';export const ADD_NEW_TODO = 'ADD_NEW_TODO'; // 定义 action 类型/*********************************** action 创建函数 *************************************//** * 更改 TODO 状态 * @param {Number} index TODO索引 * @return {Object} action */export function changeTodoStatus(index){ return {type: TOGGLE_TODO_STATUS, index};}export function addNewTodo(text){ // 定义 action 创建函数 return {type: ADD_NEW_TODO, text};}
4、修改 reducer, 响应 action
ReactReduxDemo/app/reducers/index.js
文件,修改如下:
import { combineReducers } from 'redux';import { TOGGLE_TODO_STATUS, ADD_NEW_TODO } from '../actions/index'; function todoList(state=[], action){ switch(action.type){ case TOGGLE_TODO_STATUS: var todo = state[action.index]; return [ ...state.slice(0, action.index), Object.assign({}, todo, { status: !todo.status }), ...state.slice(action.index + 1) ]; case ADD_NEW_TODO: // 定义了新的匹配类型,以响应新的 action return [ ...state, { title: action.text, status: false, } ]; default : return state; }}const reducers = combineReducers({ todos: todoList});export default reducers;
运行项目,看看是否显示了输入框与按钮。输入文字,点击按钮,看看是否添加了新的 TODO 项。
恭喜你,redux 使用已经相当熟练了。
下篇中,我们将对 TODO 进行过滤(添加新的 state, 使用 Redux 进行管理)。
- 一步一步学习 ReactNative + Redux(2)
- 一步一步学习 ReactNative + Redux(0)
- 一步一步学习 ReactNative + Redux(1)
- 一步一步学习 ReactNative + Redux(3)
- 一步一步学习 ReactNative + Redux(4:中间件)
- 一步一步学习 ReactNative + Redux(6)
- 一步一步学习 ReactNative + Redux(3.1:bug修复)
- 一步一步学习 ReactNative + Redux(3.2:优化,消除魔术字段)
- 一步一步学习 ReactNative + Redux(5:异步Action)
- ReactNative+Redux+LeanCloud开发IM(一)
- ReactNative redux 总结
- ReactNative-Redux实际应用
- ReactNative-Redux实际应用
- 基于Redux的ReactNative项目开发总结(一)
- 基于Redux的ReactNative项目开发总结(一)
- 基于Redux的ReactNative项目开发总结(二)
- react-redux学习笔记-2-react-redux
- react redux 学习2
- 二十九, iOS 因为展示版本号码被拒的的问题要注意
- Java复制文件使用进度条显示
- Python: 函数与方法的区别 以及 Bound Method 和 Unbound Method
- Linux下查看支持的信号列表
- 各种优化方法总结比较(sgd/momentum/Nesterov/adagrad/adadelta)
- 一步一步学习 ReactNative + Redux(2)
- markdown编辑器
- linux环境变量 bash_profile
- windows上配置GitHub
- Unity 特殊文件夹及脚本编译顺序
- css3新特性一
- dataTables-基础设置
- Git : SSH 协议服务器
- C语言网 1250 素数回文 原创:爱学习