寫在開始
上篇中,我們搭建了 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 項(xiàng)添加點(diǎn)擊事件锨匆,點(diǎn)擊后崭别,切換 TODO 的狀態(tài)(
status:true|false
) 冬筒; - 新建一個(gè)組件
TodoForm.component
,可以添加新的 TODO 項(xiàng)茅主。
TODO 狀態(tài)切換
1舞痰、使用 TouchableOpacity
這里我們只是給子組件 TodoListComponent
添加了點(diǎn)擊事件,沒有什么特別之處诀姚。
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){ // 點(diǎn)擊事件,通過 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赫段,并添加了點(diǎn)擊事件(注釋會報(bào)錯(cuò)呀打,請刪除注釋)
<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
的點(diǎn)擊事件已完成糯笙,通過 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 (注釋會報(bào)錯(cuò)豺憔,請刪除注釋)
</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 時(shí)酒朵,返回原始state
return state;
}
}
const reducers = combineReducers({
todos: todoList
});
export default reducers;
好了桦锄,到現(xiàn)在為止,我們已經(jīng)將 ReactNative 與 Redux 連接了起來蔫耽,并響應(yīng)了點(diǎn)擊事件结耀。
運(yùn)行項(xiàng)目留夜,點(diǎn)擊 TODO 項(xiàng),看看是否可以狀態(tài)切換了呢图甜。
添加新 TODO 項(xiàng)
到現(xiàn)在碍粥,如果對 Redux
還不太熟悉,沒關(guān)系黑毅。
接下來嚼摩,我們再來梳理與鞏固一下 Redux 工作流。
1矿瘦、新建子組件 TodoFormComponent
它有一個(gè)輸入框枕面、一個(gè)按鈕,輸入過程中缚去,將輸入對文字存入自己的 state
潮秘,點(diǎn)擊按鈕,調(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,
},
});
沒有什么特別,只是一個(gè) React 組件衬衬。
2买猖、使用 dispatch
容器組件HomeContainer
引入子組件,并定義添加新 TODO 項(xiàng)的方法滋尉,執(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)}}/> // 渲染組件(注釋會報(bào)錯(cuò),請刪除注釋)
<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,我們需要進(jìn)行定義碾篡。
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;
運(yùn)行項(xiàng)目,看看是否顯示了輸入框與按鈕穆律。輸入文字惠呼,點(diǎn)擊按鈕,看看是否添加了新的 TODO 項(xiàng)峦耘。
恭喜你剔蹋,redux 使用已經(jīng)相當(dāng)熟練了。
下篇中辅髓,我們將對 TODO 進(jìn)行過濾(添加新的 state泣崩, 使用 Redux 進(jìn)行管理)少梁。