Redux的简介和规范化的使用方法(以todoList为例)

Redux 是 JavaScript 状态容器,提供可预测化的状态管理。

Redux的核心概念主要有3个 actions、store、reducers。

actions:简单地,Actions就是事件。Actions传递来自这个应用(用户接口,内部事件比如API调用和表单提交)的数据给store。store只获取来自Actions的信息。内部Actions就是简单的具有一个type属性(通常是常量)的JavaScript对象,这个对象描述了action的类型以及传递给store的负载信息。

store:Store对象保存应用的状态并提供一些帮助方法来存取状态,分发状态以及注册监听。全部state由一个store来表示。任何action通过reducer返回一个新的状态对象。这就使得Redux非常简单以及可预测。

reducers:在函数式JavaScript中reducer基于数组reduce方法,接收一个回调(reducer)让你从多个值中获得单个值,整数和,或者一个一系列值的累积。在Redux中,reducer就是获得这个应用的当前状态和事件然后返回一个新状态的函数。理解reducer是怎样工作的至关重要,因为它们完成大部分工作。

redux安装方式:

npm install --save redux

yarn add redux

chrome配套调试插件安装(可以不装):

前提:需要科(fan)学(qiang)上网。。。

自行安装扩展:

基础使用方法:

1、创建store目录:

2、新建store/index.js文件

import { createStore } from 'redux'
import reducer from './reducer'

const store = createStore(
	reducer,
	window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() // redux的Chrome调试工具需要该参数(可以不用)
)

export default store

新建一个store,引入reducer文件,启用调试工具(可以不用),如果启用该调试器,chrome开发工具中可查看store数据。

3、新建reducer文件

import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from './actionTypes'

const defaultState = {
	inputValue: '',
	list: []
}

// reducer可以接收state,不能修改(需拷贝)
export default (state = defaultState, action) => {
	console.log(state, action) // state:上一次存储的数据  action:用户传递过来的action
	if(action.type === CHANGE_INPUT_VALUE) {
		const newState = JSON.parse(JSON.stringify(state))
		newState.inputValue = action.value
		return newState
	}
	if(action.type === ADD_TODO_ITEM) {
		const newState = JSON.parse(JSON.stringify(state))
		newState.list = [...newState.list, newState.inputValue]
		newState.inputValue = ''
		return newState
	}
	if(action.type === DELETE_TODO_ITEM) {
		const newState = JSON.parse(JSON.stringify(state))
		newState.list.splice(action.index, 1)
		return newState
	}
	return state
}

store接收到的action(事件)后,会将数据action传给reducer处理,处理方式可在此编写。

4、新建actionTypes.js文件

export const CHANGE_INPUT_VALUE = 'change_input_value'
export const ADD_TODO_ITEM = 'add_todo_item'
export const DELETE_TODO_ITEM = 'delete_todo_item'

将事件名称统一管理。

5、新建actionCreators.js文件

import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from "./actionTypes";

export const getInputChangeAction = (value) => ({
	type: CHANGE_INPUT_VALUE,
	value
})
export const getAddItemAction = () => ({
	type: ADD_TODO_ITEM
})
export const getDeleteItemAction = (index) => ({
	type: DELETE_TODO_ITEM,
	index
})

将事件的创建方式统一管理。

6、使用示例代码

import React, { Component } from 'react'
import 'antd/dist/antd.css'
import { Input, Button, List } from 'antd'
import store from './store'
import { getInputChangeAction, getAddItemAction, getDeleteItemAction } from './store/actionCreators'

class TodoList extends Component {
	constructor(props) {
		super(props)
		this.state = store.getState()
		this.handleInputChange = this.handleInputChange.bind(this)
		this.handleStoreChange = this.handleStoreChange.bind(this)
		this.handleBtnClick = this.handleBtnClick.bind(this)
		store.subscribe(this.handleStoreChange) // 只要store发生改变,就会执行参数内的方法
	}

	render() {
		return (
			<div style={{marginTop: '10px', marginLeft: '10px'}}>
				<div>
					<Input
						value={this.state.inputValue}
						placeholder='todo info'
						style={{width: '300px', marginRight: '10px'}}
						onChange={this.handleInputChange}
					/>
					<Button type='primary' onClick={this.handleBtnClick}>提交</Button>
				</div>
				<List
					style={{marginTop: '10px', width: '300px'}}
					bordered
					dataSource={this.state.list}
					renderItem={(item, index) => (<List.Item onClick={this.handleItemClick.bind(this, index)}>{item}</List.Item>)}
				/>
			</div>
		)
	}

	handleStoreChange() {
		this.setState(store.getState())
	}

	handleInputChange(e) {
		const action = getInputChangeAction(e.target.value)
		store.dispatch(action) // 提交事件给store,store会自动将他传给reducer
	}

	handleBtnClick() {
		const action = getAddItemAction()
		store.dispatch(action)
	}

	handleItemClick(index) {
		const action = getDeleteItemAction(index)
		store.dispatch(action)
	}
}

export default TodoList

该demo是个简单的Todo List:

1、store.getState()可以获取store内数据或状态;

2、通过 store.dispatch(action) 方法传给store,store传给reducer处理,处理结果保存给store,action中必须包含type字段;

3、使用 store.subscribe(function) 方法监听store变动,如果发生变动,将会执行function方法。

效果gif:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值