为什么需要react-redux
随着用户操作的复杂性,页面组件的增多,使得组件直接的状态维护和信息传递更加复杂,不利于维护。使用 redux 定义全局单一的数据 Store,可以自定义 Store 里面存放着哪些数据,整个数据结构也是自己清楚的。
react-redux是react官方退出的redux绑定库。react-redux将所有组件分为两大类:UI组件和容器组件,其中所有容器组件包裹着UI组件,构成父子关系。容器组件负责和redux交互,里面使用redux API函数,UI组件负责页面渲染,不使用任何redux API。容器组件会给UI组件传递redux中保存对的状态(state)和操作状态的方法(action)。
redux数据流向
Action
Action 是把数据从应用传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch() 将 action 传到 store。每个action是一个对象,其中type代表着要执行的操作,payload表示要操作的数据。
export function IncrementAction (payload){
return {
type:'increment',
payload
}
}
export function DecrementAction(payload){
return {
type: 'decrement',
payload
}
}
Reducer
Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。只要传入参数相同,返回计算得到的下一个 state 就一定相同。没有特殊情况、没有副作用,没有 API 请求、没有变量修改,单纯执行计算。
const initState ={
count:0
}
function count_reducers(state={...initState},action){
let count = state.count
switch (action.type){
case 'increment':
return {count: count+1};
case 'decrement':
return {count: count-1};
default:
return {count:state.count};
}
}
export default count_reducers;
Store
Store是将Action和Reducer联系在一起的对象。1)维持应用的 state;2)提供 getState() 方法获取 state;3)提供 dispatch(action) 方法更新 state;4)通过 subscribe(listener) 注册监听器。
import { createStore } from 'redux'
import countReducers from '../store/conunt_reducers'
const store = createStore(countReducers)
export default store
connect()
react-redux 提供connect方法,用于从 UI 组件生成容器组件。connect的意思,就是将这两种组件连起来。
import React from "react";
import { connect } from "react-redux";
import {IncrementAction, DecrementAction } from "../store/action";
const StoreTest = ({count,Increment,Decrement}) =>{
const increment = () => {
Increment()
}
const decrement = () => {
Decrement()
}
return (
{count}
)
}
const mapStateToProps =state=> state ;
const mapDispatchToProps = (dispatch)=>{
return {
'Increment':()=> dispatch(IncrementAction({})),
'Decrement':() => dispatch(DecrementAction({})),
}
}
export default connect(mapStateToProps,mapDispatchToProps)(StoreTest);
mapStateToProps
将state映射到 UI 组件的参数(props)。
const mapStateToProps =state=> state ;
mapDispatchToProps
将用户对 UI 组件的操作映射成 Action。
const mapDispatchToProps = (dispatch)=>{
return {
'Increment':()=> dispatch(IncrementAction({})),
'Decrement':() => dispatch(DecrementAction({})),
}
}
Provider
负责将容器组件把UI组件包裹起来,提供store属性
import React from 'react';
import ReactDOM from 'react-dom';
import StoreTest from "./component/storeTest";
import store from '../src/store/store'
import {Provider} from "react-redux";
ReactDOM.render(
,
document.getElementById('root')
);