五、redux的使用 - 图1

一、安装依赖

yarn add redux

二、项目配置

新建store文件夹
新建index.js文件
新建reducer.js文件

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

//index.js

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

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

//reducer.js

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

2-3在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. }

2-4Action

View发出的一个通知,要改变state

  • 通过一个事件派发action

    1. 1.创建一个ation,同时派发
    2. import React, { Component } from 'react';
    3. import store from '../store'
    4. class Home extends Component {
    5. constructor(props) {
    6. super(props);
    7. this.state = store.getState();
    8. }
    9. render() {
    10. return (
    11. <div>
    12. 首页
    13. <button onClick={this.handleClick}>改变store</button>
    14. </div>
    15. );
    16. }
    17. handleClick=()=>{
    18. const action = {
    19. type:"btn_change",
    20. value:"复习redux"
    21. }
    22. store.dispatch(action)
    23. }
    24. }
    25. export default Home;
  • store自动接收action,之后将action传递给reducer

  • 在reducer改变state
  1. let defaultState = {
  2. msg:"react"
  3. }
  4. //reducer可以接收state,但是不能直接修改state
  5. export default (state=defaultState,action)=>{
  6. console.log(action)
  7. switch(action.type){
  8. case "btn_change":
  9. var newState = {...state};
  10. newState.msg = action.value;
  11. return newState;
  12. default:
  13. return state;
  14. }
  15. }

订阅store的状态的改变,只要store改变,store.subscribe(fn),fn函数必然会执行

  1. class Home extends Component {
  2. constructor(props) {
  3. ...
  4. store.subscribe(this.handleStoreChange);
  5. }
  6. ...
  7. handleStoreChange=()=>{
  8. console.log(1)
  9. this.setState(store.getState())
  10. }
  11. }

三、基本概念

store 就是保存数据的地方,将store看成一个容器,一个应用只能有一个store
//如何生成一个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;

reducer 就是对state重新计算的过程就是reducer,reducer必须是函数

四、redux的调试

4-1应用商店安装redux

https://github.com/zalmoxisus/redux-devtools-extension

4-2配置

  1. import { createStore } from 'redux'
  2. import reducer from './reducer'
  3. // createStore只能接收函数
  4. let store = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
  5. export default store;