create-a-react-app zhufengredux
cd zhufengredux
cnpm install redux -S
yarn start
public\index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>React App</title>
</head>
<body>
<div id="root"></div>
<div id="counter">
<p id="counter-value">0</p>
<button id="add-btn">+</button>
<button id="minus-btn">-</button>
</div>
</body>
</html>
src\index.js
import { createStore} from './redux';
let counterValue = document.getElementById('counter-value');
let addBtn = document.getElementById('add-btn');
let minusBtn = document.getElementById('minus-btn');
const ADD = 'ADD';
const MINUS = 'MINUS';
let initState = { number: 0 };
const reducer = (state = initState, action) => {
switch (action.type) {
case ADD:
return { number: state.number + 1 };
case MINUS:
return { number: state.number - 1 };
default:
return state;
}
}
let store = createStore(reducer);
function render() {
counterValue.innerHTML = store.getState().number + '';
}
store.subscribe(render);
render();
addBtn.addEventListener('click', function () {
store.dispatch({ type: ADD });
});
minusBtn.addEventListener('click', function () {
store.dispatch({ type: MINUS });
});
src\redux\index.js
import createStore from './createStore'
export {
createStore
}
src\redux\createStore.js
const createStore = (reducer, preloadedState) => {
let state=preloadedState;
let listeners = [];
function getState() {
return state;
}
function dispatch(action) {
state = reducer(state, action);
listeners.forEach(l => l());
return action;
}
function subscribe(listener) {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
}
dispatch({ type: '@@REDUX/INIT' });
return {
getState,
dispatch,
subscribe
}
}
export default createStore;
src\index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Counter1 from './components/Counter1';
ReactDOM.render(<Counter1 />, document.getElementById('root'));
src\components\Counter1.js
import React, { Component } from 'react';
import { createStore} from '../redux';
const ADD = 'ADD';
const MINUS = 'MINUS';
const reducer = (state = initState, action) => {
switch (action.type) {
case ADD:
return { number: state.number + 1 };
case MINUS:
return { number: state.number - 1 };
default:
return state;
}
}
let initState = { number: 0 };
const store = createStore(reducer, initState);
export default class Counter extends Component {
unsubscribe;
constructor(props) {
super(props);
this.state = { number: 0 };
}
componentDidMount() {
this.unsubscribe = store.subscribe(() => this.setState({ number: store.getState().number }));
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return (
<div>
<p>{this.state.number}</p>
<button onClick={() => store.dispatch({ type: 'ADD' })}>+</button>
<button onClick={() => store.dispatch({ type: 'MINUS' })}>-</button>
<button onClick={
() => {
setTimeout(() => {
store.dispatch({ type: 'ADD' });
}, 1000);
}
}>1秒后加1</button>
</div>
)
}
}
src\components\Counter1.js
import React, { Component } from 'react';
+import { createStore,bindActionCreators} from '../redux';
const ADD = 'ADD';
const MINUS = 'MINUS';
const reducer = (state = initState, action) => {
switch (action.type) {
case ADD:
return { number: state.number + 1 };
case MINUS:
return { number: state.number - 1 };
default:
return state;
}
}
let initState = { number: 0 };
const store = createStore(reducer, initState);
+function add() {
+ return { type: 'ADD' };
+}
+function minus() {
+ return { type: 'MINUS' };
+}
+const actions = { add, minus };
+const boundActions = bindActionCreators(actions, store.dispatch);
export default class Counter extends Component {
unsubscribe;
constructor(props) {
super(props);
this.state = { number: 0 };
}
componentDidMount() {
this.unsubscribe = store.subscribe(() => this.setState({ number: store.getState().number }));
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return (
<div>
<p>{this.state.number}</p>
+ <button onClick={boundActions.add}>+</button>
+ <button onClick={boundActions.minus}>-</button>
<button onClick={
() => {
setTimeout(() => {
+ boundActions.add();
}, 1000);
}
}>1秒后加1</button>
</div>
)
}
}
src\redux\bindActionCreators.js
function bindActionCreator(actionCreator, dispatch) {
return function (...args) {
return dispatch(actionCreator.apply(this, args))
}
}
export default function bindActionCreators(actionCreators, dispatch) {
const boundActionCreators = {}
for (const key in actionCreators) {
const actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
src\redux\index.js
export {default as createStore} from './createStore'
export {default as bindActionCreators} from './bindActionCreators'
src\redux\combineReducers.js -combineReducers
src\index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Counter1 from './components/Counter1';
import Counter2 from './components/Counter2';
ReactDOM.render(<div><Counter1/><Counter2/></div>, document.getElementById('root'));
src\store\action-types.js
export const ADD1 = 'ADD1';
export const MINUS1 = 'MINUS1';
export const ADD2 = 'ADD2';
export const MINUS2 = 'MINUS2';
src\store\reducers\counter1.js
import * as types from '../action-types';
let initialState = { number: 0 }
export default function (state=initialState, action) {
switch (action.type) {
case types.ADD1:
return { number: state.number + 1 };
case types.MINUS1:
return { number: state.number - 1 };
default:
return state;
}
}
src\store\reducers\counter2.js
import * as types from '../action-types';
let initialState = { number: 0 };
export default function (state=initialState, action) {
switch (action.type) {
case types.ADD2:
return { number: state.number + 1 };
case types.MINUS2:
return { number: state.number - 1 };
default:
return state;
}
}
src\store\reducers\index.js
import { combineReducers} from '../../redux';
import counter1 from './counter1';
import counter2 from './counter2';
let rootReducer = combineReducers({
counter1,
counter2
});
export default rootReducer;
src\store\index.js
import { createStore } from '../redux';
import reducer from './reducers';
const store = createStore(reducer, { counter1: { number: 0 }, counter2: { number: 0 } });
export default store;
src\store\actions\counter1.js
import * as types from '../action-types';
const actions = {
add1() {
return { type: types.ADD1 };
},
minus1() {
return { type: types.MINUS1 };
}
}
export default actions;
src\store\actions\counter2.js
import * as types from '../action-types';
const actions = {
add2() {
return { type: types.ADD2 };
},
minus2() {
return { type: types.MINUS2 };
}
}
export default actions;
src\components\Counter1.js
import React, { Component } from 'react';
+import { bindActionCreators} from '../redux';
+import actions from '../store/actions/counter1';
+import store from '../store';
+const boundActions = bindActionCreators(actions, store.dispatch);
export default class Counter extends Component {
unsubscribe;
constructor(props) {
super(props);
this.state = { number: 0 };
}
componentDidMount() {
+ this.unsubscribe = store.subscribe(() => this.setState({ number: store.getState().counter1.number }));
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return (
<div>
<p>{this.state.number}</p>
+ <button onClick={boundActions.add1}>+</button>
+ <button onClick={boundActions.minus1}>-</button>
</div>
)
}
}
src\components\Counter2.js
import React, { Component } from 'react';
+import { bindActionCreators} from '../redux';
+import actions from '../store/actions/counter2';
+import store from '../store';
+const boundActions = bindActionCreators(actions, store.dispatch);
export default class Counter extends Component {
unsubscribe;
constructor(props) {
super(props);
this.state = { number: 0 };
}
componentDidMount() {
+ this.unsubscribe = store.subscribe(() => this.setState({ number: store.getState().counter2.number }));
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return (
<div>
<p>{this.state.number}</p>
+ <button onClick={boundActions.add2}>+</button>
+ <button onClick={boundActions.minus2}>-</button>
<button onClick={
() => {
setTimeout(() => {
+ boundActions.add2();
}, 1000);
}
}>1秒后加1</button>
</div>
)
}
}
src\redux\combineReducers.js
function combineReducers(reducers){
return function combination(state={},action){
let nextState = {};
for(let key in reducers){//key=x
//此key的老状态
let nextStateForKey = state[key];
//此key的reducer函数
let reducerForKey = reducers[key];
//把这个key老的状态和动作传给这个key对应的reducer函数,计算出新状态,然后赋值给nextState的这个key属性
nextState[key] = reducerForKey(nextStateForKey, action);
}
return nextState;
}
}
export default combineReducers;
src\redux\index.js
export {default as createStore} from './createStore'
export {default as bindActionCreators} from './bindActionCreators';
+export {default as combineReducers} from './combineReducers';
src\index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Counter1 from './components/Counter1';
import Counter2 from './components/Counter2';
import store from './store';
import { Provider } from './react-redux';
ReactDOM.render(
<Provider store={store}>
<Counter1 />
<Counter2 />
</Provider>, document.getElementById('root'));
src\components\Counter1.js
import React, { Component } from 'react';
import actions from '../store/actions/counter1';
import { connect } from '../react-redux';
class Counter1 extends Component {
render() {
let { number, add1, minus1 } = this.props;
return (
<div>
<p>{number}</p>
<button onClick={add1}>+</button>
<button onClick={minus1}>-</button>
<button onClick={
() => setTimeout(() => add1(), 1000)
}>1秒后加1</button>
</div>
)
}
}
let mapStateToProps = (state) => state.counter1;
export default connect(
mapStateToProps,
actions
)(Counter1)
src\components\Counter2.js
import React from 'react';
import { useSelector,useDispatch} from '../react-redux';
const Counter2 = (props) => {
const counter2 = useSelector(state => state.counter2);
const dispatch = useDispatch();
return (
<div>
<p>{counter2.number}</p>
<button onClick={()=>dispatch({type:'ADD2'})}>+</button>
<button onClick={()=>dispatch({type:'MINUS2'})}>-</button>
</div>
)
}
export default Counter2;
src\react-redux\Provider.js
import React from 'react'
import ReactReduxContext from './ReactReduxContext';
export default function(props){
return (
<ReactReduxContext.Provider value={{ store: props.store }}>
{props.children}
</ReactReduxContext.Provider>
)
}
src\react-redux\ReactReduxContext.js
import React from 'react';
export const ReactReduxContext = React.createContext(null)
export default ReactReduxContext;
src\react-redux\connect.js
import React, { useContext, useMemo, useReducer, useLayoutEffect } from 'react';
import ReactReduxContext from './ReactReduxContext';
import { bindActionCreators } from '../redux';
/**
* PureComponent当属性和状态没有变化的时候不重新渲染
* 刚才做的优化是有些值只计算一次,不需要反复计算
* 因为函数组件没有构造函数,没有地方说只能执行一次,只能用useMemo
* @param {*} mapStateToProps 把仓库中状态映射为当前的组件的属性
* @param {*} mapDispatchToProps 把派发动作的方法映射为组件的属性
*/
function connect(mapStateToProps, mapDispatchToProps) {
return function (OldComponent) {
return class extends React.Component {
static contextType = ReactReduxContext;
constructor(props, context) {
super(props);
const { store } = context;
const { getState, subscribe, dispatch } = store;
this.state = mapStateToProps(getState());
this.unsubscribe = subscribe(() => {
this.setState(mapStateToProps(getState()));
});
let dispatchProps;
if (typeof mapDispatchToProps === 'function') {
dispatchProps = mapDispatchToProps(dispatch);
} else if (typeof mapDispatchToProps === 'object') {
dispatchProps = bindActionCreators(mapDispatchToProps, dispatch);
} else {
dispatchProps = { dispatch };
}
this.dispatchProps = dispatchProps;
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return <OldComponent {...this.props} {...this.state} {...this.dispatchProps} />
}
}
}
}
function connect(mapStateToProps, mapDispatchToProps) {
return function (OldComponent) {
return function (props) {
const { store } = useContext(ReactReduxContext);
const { getState, dispatch, subscribe } = store;
const prevState = getState();
const stateProps = useMemo(() => mapStateToProps(prevState), [prevState]);
let dispatchProps = useMemo(() => {
console.log('dispatchProps render');
let dispatchProps;
if (typeof mapDispatchToProps === 'function') {
dispatchProps = mapDispatchToProps(dispatch);
} else if (typeof mapDispatchToProps === 'object') {
dispatchProps = bindActionCreators(mapDispatchToProps, dispatch);
} else {
dispatchProps = { dispatch };
}
return dispatchProps;
}, [dispatch]);
const [, forceUpdate] = useReducer(x => x + 1, 0);
useLayoutEffect(() => {
return subscribe(forceUpdate);
}, [subscribe]);
return <OldComponent {...props} {...stateProps} {...dispatchProps} />
}
}
}
export default connect;
src\react-redux\hooks\useDispatch.js
import {useContext} from 'react';
import ReactReduxContext from '../ReactReduxContext';
const useDispatch = ()=>{
const {store} = useContext(ReactReduxContext);
return store.dispatch;
}
export default useDispatch
src\react-redux\shallowEqual.js
export function shallowEqual(obj1, obj2) {
if (obj1 === obj2) {
return true;
}
if (typeof obj1 != "object" || obj1 === null || typeof obj2 != "object" || obj2 === null) {
return false;
}
let keys1 = Object.keys(obj1);
let keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
if (!obj2.hasOwnProperty(key) || obj1[key] !== obj2[key]) {
return false;
}
}
return true;
}
export default shallowEqual;
src\react-redux\hooks\useSelector.js
import {useContext,useLayoutEffect,useReducer,useRef} from 'react';
import { shallowEqual } from '../';
import ReactReduxContext from "../ReactReduxContext";
function useSelector(selector,equalityFn=shallowEqual){
const {store} = useContext(ReactReduxContext);
let lastSelectedState = useRef(null);
//获取仓库中的最新的状态
let state = store.getState();
let selectedState = selector(state);
//每次计算完selectedState之后会判断状态变化了没有,如果变化 了,组件会刷新,如果没变化组件不刷新
let [,forceUpdate] = useReducer(x=>x+1,0);
useLayoutEffect(()=>store.subscribe(()=>{
//比较老状态和新选中状态是否相等,如果相等,不刷新
let selectedState = selector(store.getState());
if(!equalityFn(lastSelectedState.current,selectedState)){
console.log('重新渲染');
forceUpdate();
lastSelectedState.current = selectedState;
}
}),[]);
//如何获取 最新的状态值 定义useEffect,然后给lastSelectedState.current赋值,可以在任何地方通过lastSelectedState.current取到新的值
return selectedState;
}
export default useSelector;
src\react-redux\hooks\useBoundDispatch.js
import React from 'react';
import { bindActionCreators } from '../../redux';
import ReactReduxContext from '../ReactReduxContext';
function useBoundDispatch(actions){
const {store} = React.useContext(ReactReduxContext);
let boundActions = bindActionCreators(actions,store.dispatch);
return boundActions;
}
export default useBoundDispatch;
src\react-redux\hooks\index.js
export {default as useDispatch} from './useDispatch';
export {default as useSelector} from './useSelector';
export {default as useBoundDispatch} from './useBoundDispatch';
src\react-redux\index.js
export {default as Provider} from './Provider';
export {default as connect} from './connect';
export {default as shallowEqual} from './shallowEqual';
export {useDispatch,useSelector} from './hooks';
src\components\Counter1.js
import React from 'react';
import {useDispatch,useSelector} from '../react-redux';
function Counter1(){
let state = useSelector(state=>state.counter1);//状态映射函数 connect(mapStateToProps)
let dispatch = useDispatch();
return (
<div>
<p>{state.number}</p>
<button onClick={()=>dispatch({type:'ADD1'})}>+</button>
</div>
)
}
export default Counter1;
src\components\Counter6.js
import React from 'react';
import actions from '../store/actions/counter2';
import {useSelector,useBoundDispatch} from '../react-redux';
function Counter3(){
let {number} = useSelector((state)=>state.counter2);
let boundActions = useBoundDispatch(actions);
return (
<div>
<p>{number}</p>
<button onClick={boundActions.add2}>+</button>
<button onClick={boundActions.minus2}>-</button>
</div>
)
}
export default Counter3;