一步一步學(xué)習(xí) ReactNative + Redux(2)

寫在開始

上篇中,我們搭建了 ReactNative + Redux 的結(jié)構(gòu)、顯示了初始數(shù)據(jù)。
這篇,我們需要做狀態(tài)更改了,即 dispatch(action)

源碼:https://github.com/eylu/web-lib/tree/master/ReactReduxDemo/app_step2

開發(fā)

這里,我們的任務(wù)如下:

  • 給 TODO 項添加點擊事件,點擊后,切換 TODO 的狀態(tài)(status:true|false) ;
  • 新建一個組件TodoForm.component,可以添加新的 TODO 項。

TODO 狀態(tài)切換

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 調(diào)用容器組件的方法
        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 調(diào)用容器組件的方法。容器組件 HomeContainer 調(diào)用 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 里解構(gòu)出 dispatch
        dispatch(changeTodoStatus(index));          // 執(zhí)行 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、創(chuàng)建 action

這里,我們使用方法創(chuàng)建 action ,并將 action 的 type 字段全部使用常量(不直接使用字符串,方便統(tǒng)一管理與多處引用)

新建文件 ReactReduxDemo/app/actions/index.js,如下:

/*********************************** action 類型常量 *************************************/

/**
 * 更改 TODO 狀態(tài)
 * @type {String}
 */
export const TOGGLE_TODO_STATUS = 'TOGGLE_TODO_STATUS';

/*********************************** action 創(chuàng)建函數(shù) *************************************/

/**
 * 更改 TODO 狀態(tài)
 * @param  {Number} index TODO索引
 * @return {Object}       action
 */
export function changeTodoStatus(index){
    return {type: TOGGLE_TODO_STATUS, index};
}

4、使用 reducer 更新 state

還沒完,我們創(chuàng)建了action,并且派發(fā)了action。但是,還沒有響應(yīng)action。我們需要用reducer響應(yīng)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){                                  // 匹配響應(yīng) action,創(chuàng)建并返回新的 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;

好了,到現(xiàn)在為止,我們已經(jīng)將 ReactNative 與 Redux 連接了起來,并響應(yīng)了點擊事件。
運行項目,點擊 TODO 項,看看是否可以狀態(tài)切換了呢。

Paste_Image.png

添加新 TODO 項

到現(xiàn)在,如果對 Redux 還不太熟悉,沒關(guān)系。
接下來,我們再來梳理與鞏固一下 Redux 工作流。

1、新建子組件 TodoFormComponent

它有一個輸入框、一個按鈕,輸入過程中,將輸入對文字存入自己的 state,點擊按鈕,調(diào)用 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);    // 調(diào)用父組件方法
    }

    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 項的方法,執(zhí)行 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 里解構(gòu)出 dispatch
        dispatch(addNewTodo(text));                // 執(zhí)行 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 狀態(tài)
 * @type {String}
 */
export const TOGGLE_TODO_STATUS = 'TOGGLE_TODO_STATUS';

export const ADD_NEW_TODO = 'ADD_NEW_TODO';               // 定義 action 類型

/*********************************** action 創(chuàng)建函數(shù) *************************************/

/**
 * 更改 TODO 狀態(tài)
 * @param  {Number} index TODO索引
 * @return {Object}       action
 */
export function changeTodoStatus(index){
    return {type: TOGGLE_TODO_STATUS, index};
}

export function addNewTodo(text){                        // 定義 action 創(chuàng)建函數(shù)
    return {type: ADD_NEW_TODO, text};
}

4、修改 reducer, 響應(yīng) 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:                                // 定義了新的匹配類型,以響應(yīng)新的 action
            return [
                ...state,
                {
                    title: action.text,
                    status: false,
                }
            ];
        default :                                         
            return state;
    }

}

const reducers = combineReducers({
    todos: todoList
});

export default reducers;

運行項目,看看是否顯示了輸入框與按鈕。輸入文字,點擊按鈕,看看是否添加了新的 TODO 項。
恭喜你,redux 使用已經(jīng)相當熟練了。

Paste_Image.png

下篇中,我們將對 TODO 進行過濾(添加新的 state, 使用 Redux 進行管理)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容