存储数据
更改数据
连接store和action的纯函数
将传入的state和action结合,生成一个新的state
dispatch
派发action修改storesubscribe | unsubscribe
订阅store的数据发生变化// store/index.js
import { createStore } from 'redux';
const initState = {
msg: "hello redux"
}
/*** 定义reducer,纯函数*****/
function reducer(state = initState, action){
if (action.type === "change"){
return {...state, msg: action.payload.msg};
}
return state;
}
export default const store = createStore(reducer);
// store/ actionCreator.js
/**** 动态生成action *****/
export const CHANGEMSGACTION = msg => ({type: 'change', payload: {msg}});
// 使用的地方
import store from "~/store";
const unsubscribe = store.subscribe(() => {
console.log("::::STORE", store.getState());
})
unsubscribe();
// 修改store中的数据
const MSGAction = {
type: "change",
payload: {
msg: "hello change",
}
};
store.dispatch(MSGAction);
combineReducer
将多个reducer合并为一个reducer,达到拆分store的目的一个 store
中:action
,不要试图在其他地方通过任何的方式来修改State:reducer
将 旧state和 actions联系在一起,并且返回一个新的State:provider
给整个app提供store// App.jsx
import { Provider } from 'react-redux';
import store from '~/store';
const root = document.querySelector("#root");
root.render(
<Provider store={store}>
<App/>
</Provider>
)
connect
将组件和store
连接。connect会返回一个高阶组件,接受的参数将store中的部分数据映射到组件// 组件中
import React, { PureComponent } from "react";
import { connect } from "react-redux";
class MyComp extends PureComponent{
render(){
const { msg, changeMsg } = this.props;
return (<div>
<h2>{msg}</h2>
<input onChange={val => changeMsg(val)} />
</div>
}
}
/**** 将state映射到props,组件中props中就会有msg ****/
function mapStateToProps(state){
return {
msg: state.msg
}
}
/*** 将修改store的函数添加到组件的props中 ***/
function mspDispatchToProps(dispatch){
return {
changeMsg(msg){
dispatch(CHANGEMSGACTION(msg));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MyComp);
异步action
—中间件
createStore
的第二个参数接受一个中间件,使用react-thunk
使得dispatch可以派发函数,在派发的函数中可以异步更新store。import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const reducer = (state, action) => {
...
return state;
}
const store = createStore(reducer, applyMiddleware(thunk));
// actionCreator.js
...
/**** 被派发的函数,需要返回一个函数,该函数接受两个参数dispatch,getState,*****/
const fetchHomeDataAction = () => {
return (dispatch, getState) => {
fetch(url).then(res => {
dispatch(HOMEDATAACTION(res.data));
});
}
}
// 组件中
function mapDispatchToProps(dispatch){
return {
fetchHomeData(){
dispatch(fetchHomeDataAction()); // 执行action函数
}
}
}
npm install @reduxjs/toolkit react-redux
createSlice({name, initialState, reducers:{}})
接受reducer函数的对象、切片名称和初始状态值,并自动生成切片reducer,并带有相应的actions。
import { createSlice } from '@reduxjs/toolkit';
const CounterSlice = createSlice({
name: "counter",
initialState: {
count: 0,
},
reducers: {
addNumber(state, action){
state.counter += action.payload;
}
}
});
export const { addNumber } = CounterSlice.action;
export default CounterSlice.reducer;
configureStore
包装createStore以提供简化的配置选项和良好的默认值。它可以自动组合你的 slice reducer,添加你提供的任何 Redux 中间件,redux-thunk默认包含,并启用 Redux DevTools Extension。const store = configureStore({
reducer: {
counter: counterReducer;
}
})
createAsyncThunk
接受一个动作类型字符串和一个返回承诺的函数,并生成一个pending/fulfilled/rejected基于该承诺分派动作类型的 thunkconst AXIOSDataSlice = createSlice({
name: 'axiosdata',
initialState: {
data: []
},
reducers: {
setData(state, action){
state.data = action.payload;
}
},
extraReducers: {
/**
[AxiosMultidataAction.pending](state, action){
state.data = action.payload;
}
[AxiosMultidataAction.rejected](state, action){
state.data = action.payload;
}
**/
[AxiosMultidataAction.fulfilled](state, action){
state.data = action.payload;
}
}
/*** 链式写法 *****/
extraReducers: (builder) => {
builder.addCase(AxiosMultidataAction.pending, (state, action) => {
console.log("pending");
}).addCase(AxiosMultidataAction.fulfilled, (state, action) => {})
}
})
export default AXIOSDataSlice.reducer;
const AxiosMultidataAction = createAsyncThunk("axiosdata", async (extraInfo, store) => {
// 第一个can
const res = await getData();
return res;
})
immerjs
库保持数据不可变(持久化数据
)function connect(mapStateToProps, mapDispatchToProps){
function hoc(Component){
class HOCComponent extends PureComponent{
constuctor(props){
super(props);
this.state = mapStateToProps(store.getState());
}
componentDidMount(){
this.unsubscribe = store.subscribe(() => {
//this.forceUpdate();
this.setState(mapStateToProps(store.getState());
})
}
componentWillUnmount() {
this.unsubscribe();
}
render(){
return <Component {...this.props} {...mapStateToProps(store.getState())} {...mapDispatchToProps(store.dispatch)} />
}
}
return HOCComponent;
}
return hoc;
}