一、redux概念
Redux的三大原则
二、在非脚手架中使用redux
redux是一个单独的库,所以可以在普通项目、vue、react中使用。
三、react中使用redux
我的理解是,createStore时必须有一个reducer函数,
store会主动调用reducer函数返回的state作为初始state;
后续,当我们使用dispatch取修改的时候,redux会主动调用reducer,然后reducer内部去做修改然后返回一个全新的state,
由于createStore是跟reducer强绑定的,所以store的数据也就跟着改变了。
第一:npm install redux
第二:专门建一个store文件夹,去实例化一个store,并且这个store的数据是由reducer提供的。
第三:其他组件可以通过store.getState取获取store数据的初始值
第四:想要修改store里的值,需要用到store.dispatch({type:'xxxxxx', params);
第五:当我们dispatch时,redux会自动帮助我们调用reducer函数,所以我们需要在reducer函数里做处理
reducer函数有两个参数,一个是旧state,一个是本次提出dispatch的action对象。
经过处理后,返回一个新的state(记住,reducer是一个纯函数,所以不要修改原旧state,要返回一个新的state。)
第六: redux把旧的state更新成reducer新返回的state
第七:通知所有订阅过(store.subcribe())的组件
import { createStore } from 'redux'; import * as actionTypes from './constants';// 定义常量 export const ADD_NUMBER = 'add_number'; export const SUB_NUMBER = 'sub_number';// 定义action export const addNumberAction = num => ({type: ADD_NUMBER,num});export const subNumberAction = num => ({type: SUB_NUMBER,num});// 定义reducer函数 const initialState = {counter: 0 }; export function reducer(state = initialState, action) {switch (action.type) {case actionTypes.ADD_NUMBER:return { ...state, counter: state.counter + action.num };case actionTypes.SUB_NUMBER:return { ...state, counter: state.counter - action.num };default:return state;} }// 实例化store const store = createStore(reducer);export default store;
export class App extends PureComponent {constructor() {super();this.state = {counter: store.getState().counter};}componentDidMount() {store.subscribe(() => this.setState({ counter: store.getState().counter }));}render() {const { counter } = this.state;return (<div><h1>App{counter}<Home></Home><Profile></Profile></h1></div> );} }export default App;
import React, { PureComponent } from 'react' import store from "../store" import { addNumberAction } from '../store/counter'export class Home extends PureComponent {constructor() {super()this.state = {counter: store.getState().counter,}}componentDidMount() {store.subscribe(() => {const state = store.getState()this.setState({ counter: state.counter })})}addNumber(num) {store.dispatch(addNumberAction(num))}render() {const { counter } = this.statereturn (<div><h2>Home Counter: {counter}</h2><div><button onClick={e => this.addNumber(1)}>+1</button><button onClick={e => this.addNumber(5)}>+5</button><button onClick={e => this.addNumber(8)}>+8</button></div></div> )} }export default Home