简介
安装
npm install --save redux,react-redux
- 其中
react-redux
是将react和redux结合起来的包,他提供了Provider
和connect
函数来简化redux的使用 点击
核心概念
理念
store
是唯一的数据源- 数据源只能通过
action
来改变状态 reducer
是用来链接store
与action
的,返回一个新的state
原则
- 单一数据源
- 整个应用程序的state只能存储在一个store中
- 这样会使state变得容易维护和追踪
- state是只读的
- 修改state的方法一定是触发
action
- 所有的修改都是集中化处理,避免其他的问题
- 修改state的方法一定是触发
- 使用纯函数来执行修改
- 随着应用程序的复杂度增加,我们可以将
reducer
拆分成多个小的reducers
,分别操作不同state tree
的一部分 - reducer应该为纯函数
- 随着应用程序的复杂度增加,我们可以将
纯函数
简单的说是输入决定输出
- 纯函数
function(a,b){
return a + b
}
- 对比
// 非纯函数
let num1 = 10;
function sum(num2){
return num1 + num2;
}
// 纯函数
const num1 = 10;
function sum(num2){
return num1 + num2;
简单使用
一般约定俗成的,我们在src下新建store的文件夹,当前文件夹专门用于管理状态,然后定义一下文件夹
状态库
也就是
store
文件夹
types.js
export const ADD_COUNT = Symbol('ADD_COUNT');
export const SUB_COUNT = Symbol('SUB_COUNT');
actions.js
import { ADD_COUNT, SUB_COUNT } from "./types";
export const addAction = (num) => {
return { type: ADD_COUNT, num: num };
};
export const subAction = (num) => {
return { type: SUB_COUNT, num: num };
};
reducer.js
import {ADD_COUNT,SUB_COUNT} from './types'
let initState = {
count:0
}
function reducer(state=initState,action){
// 最终返回一个新的state
switch(action.type){
case ADD_COUNT:
return {count:state.count + action.num};
case SUB_COUNT:
return {count:state.count - action.num}
default:
return state
}
}
export default reducer
store.js
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
事实上官方已经不再推荐这种写法,可以改成如下的写法,点击
入口文件
在入口文件我们需要使用
Provider
组件,将状态提供给全局
import {Provider} from 'react-redux'
import store from './store/store';
ReactDOM.createRoot(document.getElementById('root')).render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>
)
组件
在组件中我们需要将redux中的状态映射到当前的组件
import React from 'react';
import { connect } from 'react-redux';
import {addAction, subAction} from '../store/actions';
class Home extends React.PureComponent{
render(){
const {increment,count,decrement} = this.props
return (
<div>
{/* 3.通过props来使用redux中保存的数据 */}
<p>{count}</p>
<button onClick={increment}>递增</button>
<button onClick={decrement}>递减</button>
</div>
)
}
}
const mapStateToProps = (state)=>{
return{
count: state.count
}
}
const mapDispatchToProps = (dispatch)=>{
return{
increment(){
dispatch(addAction(1));
},
decrement(){
dispatch(subAction(2))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
这里需要使用react-redux
的connect
函数
- 他是一个高级函数,所谓高级函数就是返回一个函数,然后还可以调用
- 接收一个组件作为参数
connect
的参数常用的有mapStateToProps
:store
中保存的哪些数据映射到当前组件的props
上mapDispatchToProps
:需要将哪些派发的任务映射到当前组件的props
上