redux的使用
redux的使用主要包括三部分store仓库
reduce函数
action
store仓库里储存着所有公共状态,通过dispatch触发action,reduce函数一直处于监听状态,当有匹配的type时返回其状态。
store
store.js
// applyMiddleware: redux通过该函数来使用中间件
// createStore: 用于创建store实例
import {createStore,applyMiddleware} from 'redux'
//thunk中间件可以支持异步action
import thunk from 'redux-thunk'
// import reducer from './reduce'
import reducer from './reduce'
const store = createStore(reducer,applyMiddleware(thunk))
// console.log(store.getState());
export default store
action
action.js
import { ADDONE } from "./actionTypes"
export const jiaYi=() =>( {
type:ADDONE
})
其中包括常量的引入
actionTypes.js
export const ADDONE = 'ADDONE';
reduce
reduce.js
import { ADDONE , ADDTWO} from "./actionTypes"
import { combineReducers } from 'redux'
const add = (state=0,action)=>{
// let newState = JSON.parse(JSON.stringify(state))
switch(action.type){
case ADDONE:
// newState = state.num+1;
return state+1;
case ADDTWO :
// newState = state.num+2;
return state+2;
default :
return state
}
}
const add1 = (state=0,action)=>{
// let newState = JSON.parse(JSON.stringify(state))
switch(action.type){
case ADDONE:
// newState = state.num+1;
return state+1;
case ADDTWO :
// newState = state.num+2;
return state+2;
default :
return state
}
}
// 合并reduce,并把状态合并成一个大状态
const reducer = combineReducers({
add,
add1
})
export default reducer
Appp
Appp.js
import './App.css';
import { connect } from 'react-redux'
import { Component } from 'react';
import { jiaYi } from './action';
class Appp extends Component {
onClick = () => {
console.log(this.props.dispatch(jiaYi()));
}
render() {
// console.log(store.getState());
return (
<div className="App">
<button className="btn" onClick={this.onClick}>点击</button>
<div>{this.props.add}</div>
{/* 使用了mapStateToProps函数,此时props里面就有dispatch函数,既不用特意写store了 */}
</div>
);
}
}
// o有了这个函数,才能在每次仓库数据发生变化的时候重新渲染
const mapStateToProps = (state) => {
return {
// 这个add就是reduce里面的函数
add: state.add
}
}
// connect将mapStateToProps这个函数给APPP使用
export default connect(mapStateToProps)(Appp);