react-redux
Redux 官方提供的 React 绑定库。 具有高效且灵活的特性。
<Provider store> 使组件层级中的 connect() 方法都能够获得 Redux store。正常情况下,你的根组件应该嵌套在 <Provider> 中才能使用 connect() 方法。connect 本质也是一个高阶组件
// app.js
import React from 'react';
import {Provider} from 'react-redux'
import ReduxTest from "./ReduxTest";
import store from "../store";
function App() {
return (
<div className="App">
// 原理同context
<Provider store={store}>
<ReduxTest></ReduxTest>
</Provider>
</div>
)
}
export default App;
ReactDOM.render(
<Provider store={store}>
<ReduxTest></ReduxTest>
</Provider>
)
// store.js
import {createStore} from 'redux'
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'add':
return state + 1;
case 'minus':
return state - 1
default:
return state
}
}
const store = createStore(counterReducer)
export default store
// ReduxTest.js
import React from "react";
import {connect} from 'react-redux'
// connect本质是一个工厂函数
const mapStateToProps = state => ({num: state})
const mapDispatchToProps = {
add: () => ({type: "add"}),
minus: () => ({type: "minus"})
}
function ReduxTest({num, add, minus}) {
return <div>
<p>{num}</p>
<div>
<button onClick={add}> +</button>
<button onClick={minus}> -</button>
</div>
</div>
}
export default connect(mapStateToProps, mapDispatchToProps)(ReduxTest)
// 以下是重构
// store/index.js
import {createStore, applyMiddleware, combineReducers} from 'redux'
import logger from 'redux-logger' // 日志记录
import thunk from 'redux-thunk' // 异步处理方案
import {counterReducer} from './count.redux'
// combineReducers 将多个reducer变成一个
// applyMiddleware 可以理解为是一个高阶函数,在dispatchReducer提前整合成一个函数,并返回store
const store = createStore(
combineReducers({'counter': counterReducer})
, applyMiddleware(logger, thunk))
// const store = createStore(counterReducer, applyMiddleware(logger, thunk))
export default store
// store/count.redux.js
export const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'add':
return state + 1;
case 'minus':
return state - 1
default:
return state
}
}
// action creator
export const add = () => ({type: "add"});
export const minus = () => ({type: "minus"});
export const asyncAdd = () => dispatch => {
// 异步操作
setTimeout(() => {
dispatch({type: "add"})
}, 2000)
};
// ReduxTest.js
import React from "react";
import {connect} from 'react-redux'
import {add, minus, asyncAdd} from '../store/count.redux'
const mapStateToProps = state => ({num: state.counter})
const mapDispatchToProps = {add, minus, asyncAdd}
// 装饰器写法
@connect(mapStateToProps, mapDispatchToProps)
class ReduxTest extends React.Component {
render() {
const {num, add, minus, asyncAdd} = this.props
return (
<div>
<p>{num}</p>
<div>
<button onClick={add}> +</button>
<button onClick={minus}> -</button>
<button onClick={asyncAdd}> asyncAdd</button>
</div>
</div>
);
}
}
export default ReduxTest