一步一步学习 ReactNative + Redux(2)

写在开始

上篇中,我们搭建了 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 是我们想注入的 props
function 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 项,看看是否可以状态切换了呢。


Paste_Image.png

添加新 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';   // 引入新 action

import 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 是我们想注入的 props
function 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 使用已经相当熟练了。


Paste_Image.png

下篇中,我们将对 TODO 进行过滤(添加新的 state, 使用 Redux 进行管理)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值