pic.png

0、基本概念

  1. store 就是保存数据的地方,将store看成一个容器,一个应用只能有一个store
  2. //如何生成一个store createStore
  1. //store--index.js
  2. import { createStore } from 'redux'
  3. const defaultState = {
  4. msg:"react很不好用"
  5. }
  6. const reducer = (state=defaultState,action)=>{
  7. return state;
  8. }
  9. // createStore只能接收函数
  10. let store = createStore(reducer);
  11. export default store;
  1. reducer 就是对state重新计算的过程就是reducer,reducer必须是函数

1、安装依赖

  1. yarn add redux

2、项目配置

  1. store
  2. --index.js
  3. --reducer.js

2-1、创建store容器,管理数据

  1. //index.js
  2. import {createStore} from 'redux';
  3. import reducer from './reducer';
  4. const store = createStore(reducer);
  5. export default store;

2-2、创建reducer,接收action,重新计算state

  1. //reducer.js
  2. let defaultState = {
  3. msg:"react"
  4. }
  5. export default (state=defaultState,action)=>{
  6. return state
  7. }

3-1、在Home.js中导入store(需要在哪里使用就在哪里导入)

  1. import store from '../store'js
  2. class Home extends Component {
  3. constructor(props) {
  4. super(props);
  5. this.state = getState();
  6. }
  7. ....
  8. }

3-2、action(View发出的一个通知,要改变state)

  1. //通过一个事件派发action
  2. 1.创建一个ation,同时派发
  3. class Home extends Component {
  4. ...
  5. render() {
  6. return (
  7. <div>
  8. <button onClick={this.handleClick}>改变store</button>
  9. </div>
  10. );
  11. }
  12. handleClick=()=>{
  13. const action = {
  14. type:"btn_change",
  15. value:"复习redux"
  16. }
  17. store.dispatch(action)
  18. }
  19. }
  20. export default Home;
  1. //2.store自动接收action,之后将action传递给reducer
  1. //3.在reducer改变state
  2. let defaultState = {
  3. msg:"react"
  4. }
  5. //reducer可以接收state,但是不能直接修改state,所以这里做一个深拷贝
  6. export default (state=defaultState,action)=>{
  7. //看数据派发过来没有
  8. console.log(action)
  9. switch(action.type){
  10. case "btn_change":
  11. var newState = {...state};
  12. newState.msg = action.value;
  13. return newState;
  14. default:
  15. return state;
  16. }
  17. }
  1. //4.订阅store的状态的改变,只要store改变,store.subscribe(fn),fn函数必然会执行
  2. class Home extends Component {
  3. constructor(props) {
  4. ...
  5. store.subscribe(this.handleStoreChange);
  6. }
  7. ...
  8. handleStoreChange=()=>{
  9. console.log(1)
  10. this.setState(store.getState())
  11. }
  12. }