redux 的简单实用案例
整体思想与结构
文件目录如下:
- 构建 action,通过创建一个函数,然后返回一个对象,注意需
要携带 type 属性 - 构建 reducer,用来响应 action,然后通过 return 把数据传回
给 store - 利用 createStore 来构建 store,构建的时候传递我们写好的
reducer - 利用 store.subscribe() 注册监听
- 当我们利用store.dispatch()发送一个action的时候就能触发我
们的监听了,在里面利用 store.getState()就能拿到值
创建一个Action
- 在根目录下创建一个文件夹action
- 在该目录下创建一个 index.js 文件,用来 构建Action
const sendAction = () => {...} ;
- 在 action创建函数里面 利用return,返回一个action对象,注意需要携带type属性
const sendAction = () => {return {type: "aend action",value:"发送了一个action"}}
- 把这个action创建函数进行导出
module.exports = {sendAction}
整体代码如下
/**
* 这是 action 的构造函数
*/
const sendAction = () => ({
type : 'send_type',
value: '我是一个action'
})
module.exports = {
sendAction
};
创建一个Reducer
- 在根目录下创建一个文件夹 reducer
- 在该目录下创建一个 index.js 文件,用来 构建 reducer,注意reducer要接收两个参数
conat rootReducer (state, action) => {...};
• 第一个参数是默认状态,我们可以定义一个初始化的 state,然后进行赋值
const initState = {value:'默认值'}
const rootReducer = (state = initState , action) => {...};
- 在函数里面判断第二个参数 action的type值是否是我们发送的
- 如果是的话,我们可以通过 return 返回新的 state
整体代码如下
/**
* 这个文件是 创建 reducer 函数的,专门用来处理 发送过来的action
*/
const initState = {
value : '默认值'
}
const reducer = (state = initState, action) => {
console.log('我被调用了');
return action['type'] === 'send_type' ? Object.assign({}, state, action) : state;
}
module.exports = {
reducer
}
创建Store
- 在根目录下创建一个文件夹 store
- 在该目录下创建一个 index.js 文件,用来 构建 store,注意 createStore 函数里面第一个参数接收的是 reducer
import { createStore } from "redux";
const store = createStore(reducer) ;
- 我们需要导入 刚刚创建的 reducer,然后设置到函数里面去
- createStore的返回值就是我们构建好的 store,然后进行导出
整体代码如下
import {createStore} from 'redux';
//导入我们自己创建好的 reducer
import {reducer} from './../reducer';
// 构建 store
const store = createStore(reducer);
export default store;
在App组件开始使用
- 给页面的button按钮绑定一个点击事件
- 在组件一加载完毕的时候我们通过 store来进行 监听器的注册,返回值可以用来注销监听
this.unSubbscribe = store.subscribe(() =>{...});
- 在点击事件处理函数中,通过 store.dispatch来发送一个action
handleClick () => {store.dispatch(sendAction()) };
整体代码如下
import React, { Component } from 'react';
import store from './store';
import {sendAction} from './action';
export default class App extends Component {
handleClick = () => {
const action = sendAction();
store.dispatch(action);
}
componentDidMount() {
store.subscribe(() => {
console.log('subscribe', store.getState());
this.setState({})
});
}
render() {
return (
<>
<button onClick={this.handleClick}>点我,发送一个action</button>
<div>{store.getState().value}</div>
</>
)
}
}