Redux(简单版本)
1.安装redux
npm i redux
2.配置store
// 引入createStore
// store.js
import { createStore } from "redux";
import countReducer from "./count_reducer";
export default createStore(countReducer);
3.配置reducer
// count_reducer.js
const countReducer = (prevState = 0, action) => {
const { type, data } = action;
switch (type) {
case "increment":
return prevState + data;
case "decrement":
return prevState - data;
default:
return prevState;
}
};
export default countReducer;
4.组件中使用
store.getState()获取数据
// Count.jsx
import store from "../../redux/store";
const [count,setCount] = useState(store.getState())
<div>当前求和为: {count}</div>
store.dispatch()
const increment = ()=>{
store.dispatch({type:'increment',data:'xxx'})
}
//这样调用后count 并不会引起变化,此时需要store的另一个api
store.subscribe()
//在类式组件中:这个api 需要在componentDidMount 钩子中调用,并且需要主动调用this.setState()来主动刷新页面重新渲染。
componentDidMount(){
store.subscribe(()=>{
this.setState({}) // 传入空对象,目的是让页面再次刷新下
})
}
// 函数式组件中:
const [count,setCount] = useState(store.getState())
useEffect(()=>{
store.subscribe(()=>{
setCount(store.getState()) // 此处目的同样是重新渲染页面
})
},[])