文章目录
本文已收录在 Github
: https://github.com/beichensky/Blog 中,欢迎 Star!
写在前面
本文代码通过 create-react-app
脚手架进行搭建,所有的代码均可直接复制运行。
代码位置:react-redux-demo
本文主要讲解了 Redux 和 React-Redux 的使用,详细的概念以及设计思想请看 Redux 中文官网
- 使用
create-react-app
创建React
项目
# npx
npx create-react-app my-app
# npm
npm init react-app my-app
# yarn
yarn create react-app my-app
- 安装
redux
npm install redux
# or
yarn add redux
一、Action 描述更新对象
是把数据从组件传到 store
的载体,是修改 store
数据的唯一来源。
是一个普通的 javascript
对象,必须包含一个 type
属性,用来通知 reducer
这个 action
需要做的操作类型。
比如:
{
type: 'ADD',
payload: 1
}
通过 store.dispatch(action)
将 action
传给 store
二、Reducer 执行更新函数
描述 store
数据如何更新的纯函数,接受两个参数
-
state
:store
中的state
值,可以给state
设置初始值 -
action
:通过store.dispatch(action)
传递的action
对象
通过 action
的 type
类型来判断如何更新 state
数据
比如:
function reducer(state = 0, {
type, payload }) {
switch (type) {
case "ADD":
return state + payload;
case "DELETE":
return state - payload;
default:
return state;
}
}
三、Store
将 action
和 reducer
联系到一起的对象,具有以下职责
- 维持应用的
state
- 提供
getState()
方法获取state
- 提供
dispatch(action)
方法更新state
- 通过
subscribe(listener)
注册监听器; - 通过
subscribe(listener)
返回的函数注销监听器
store
的创建方式
const store = createStore(reducer[, prevState, ehancer]);
四、实现一个简单的 React 计数器
- 通过
store.dispatch(action)
通知数据更新 - 通过
store
获取state
数据 - 编写
reducer
实现数据更新
store/index.js
import {
createStore } from "redux";
// 创建 reducer 函数 ,更新 state 数据
const reducer = function(state = 0, {
type }) {
switch (type) {
case "INCREMENT":
return ++state;
case "DECREMENT":
return --state;
default:
return state;
}
};
// 创建 store
const store