React18中classnames库的使用,Redux的详细使用,react中使用redux,react-redux使用

145 阅读4分钟

Vue中添加class

image.png

React中添加class

image.png

React18中classnames库的使用

npm i classnames

import React, { PureComponent } from "react";
import classNames from "classnames";
export class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      isbbb: false,
      isccc: true,
    };
  }
  render() {
    const { isbbb, isccc } = this.state;

    const classList = ["aaa"];
    if (isbbb) classList.push("bbb");
    if (isccc) classList.push("ccc");
    const classname = classList.join(" ");
    return (
      <div>
        <h2 className={`aaa ${isbbb ? "bbb" : ""}  ${isccc ? "ccc" : ""}`}>hahaha</h2>
        <h2 className={classname}>zm</h2>

        <h2 className={classNames("aaa", { bbb: isbbb, ccc: isccc })}>嘿嘿嘿</h2>
        <h2 className={classNames(["aaa", { bbb: isbbb, ccc: isccc }])}>嘻嘻嘻</h2>
      </div>
    );
  }
}
export default App;

image.png

Redux的详细使用

理解js纯函数

image.png

副作用概念的理解

image.png

纯函数的作用和优势

image.png

纯函数案例

image.png

判断是否是纯函数

image.png

为什么需要redux

image.png

Redux的核心概念-state

image.png

Redux的核心理念-action

image.png

Redux的核心理念-reducer

image.png

使用store中的数据

npm i redux

const { createStore } = require("redux");
// 初始化数据
const initState = {
  name: "zm",
  counter: 100,
};
// 定义reducer函数:纯函数
function reducer() {
  return initState;
}
// 创建的store
const store = createStore(reducer);
module.exports = store;

image.png

Redux的三大原则

image.png

Redux的使用过程

image.png

Redux使用流程

image.png

image.png

Redux结构划分

image.png

image.png

优化

image.png

代码(根据上图从上到下):

                                               actionCreators.js
const { CHANGE_NAME, ADD_COUNT } = require("./constants");
const changeNameAction = (name) => ({
  type: CHANGE_NAME,
  name,
});
const addCountAction = (num) => ({
  type: ADD_COUNT,
  num,
});
module.exports = {
  changeNameAction,
  addCountAction,
};
                                                constants.js
const ADD_COUNT = "add_count";
const CHANGE_NAME = "change_name";

module.exports = {
  ADD_COUNT,
  CHANGE_NAME,
};
                                                index-if判断.js
const { createStore } = require("redux");
// 初始化数据
const initState = {
  name: "zm",
  count: 100,
};
// 定义reducer函数:纯函数
// 两个参数
// 参数1:store中目前保存的state
// 参数2:本次需要更新的action(dispatch传入的action)
// 返回值:它的返回值会作为store之后存储的state
function reducer(state = initState, action) {
  // 有数据进行更新的时候,那么返回一个新的state
  if (action.type === "change_name") {
    return { ...state, name: action.name };
  } else if (action.type === "add_count") {
    return { ...state, count: state.count + action.num };
  }

  // 没有新数据更新,那么返回之前的state
  return state;
}
// 创建的store
const store = createStore(reducer);
module.exports = store;
                                               index.js
const { createStore } = require("redux");
const reducer = require("./reducer");

/**
 * redux代码优化
 * 1.将派发的action生成过程放到一个actionCreators函数中
 * 2.将定义的所有的actionCreators的函数,放到一个独立的文件中actionCreators.js
 * 3.actionCreator和reducer函数中使用字符串常量是一致的,将常量抽取到独立的constants文件中
 * 4.将reducer和默认值放到一个独立的reducer.js文件中,而不是在index.js
 */

// 创建的store
const store = createStore(reducer);
module.exports = store;
                                               reducer.js
const { CHANGE_NAME, ADD_COUNT } = require("./constants");
// 初始化数据
const initState = {
  name: "zm",
  count: 100,
};
// 定义reducer函数:纯函数
// 两个参数
// 参数1:store中目前保存的state
// 参数2:本次需要更新的action(dispatch传入的action)
// 返回值:它的返回值会作为store之后存储的state
function reducer(state = initState, action) {
  switch (action.type) {
    case CHANGE_NAME:
      return { ...state, name: action.name };
    case ADD_COUNT:
      return { ...state, count: state.count + action.num };
    default:
      return state;
  }
}
module.exports = reducer;
                                          01使用store中的数据.js
const store = require("./store/index-if判断");
console.log(store.getState());
                                          02修改store中的数据.js
const store = require("./store/index-if判断");
console.log(store.getState());
// 修改store中的数据:必须通过action
const nameAction = { type: "change_name", name: "zm6" };
store.dispatch(nameAction);
console.log(store.getState());
// 修改count
const countAction = { type: "add_count", num: 10 };
store.dispatch(countAction);
console.log(store.getState());
                                         03订阅store中的数据.js
const store = require("./store/index-if判断");
// store.subscribe(() => {
//   // 只要派发action,就会执行
//   console.log("订阅数据的变化:", store.getState());
// });
// 取消订阅
const unsubscribe = store.subscribe(() => {
  // 只要派发action,就会执行
  console.log("订阅数据的变化:", store.getState());
});
// 修改store中的数据:必须通过action
store.dispatch({ type: "change_name", name: "ww" });
store.dispatch({ type: "change_name", name: "dhs" });
unsubscribe();
// 修改count
store.dispatch({ type: "add_count", num: 10 });
                                      04动态生成action-函数.js
const store = require("./store/index-if判断");
// actionCreators:帮助我们创建action
const changeNameAction = (name) => ({
  type: "change_name",
  name,
});
// 箭头函数返回 对象
const addCountAction = (num) => ({
  type: "add_count",
  num,
});
const unsubscribe = store.subscribe(() => {
  // 只要派发action,就会执行
  console.log("订阅数据的变化:", store.getState());
});
// 修改store中的数据:必须通过action
// store.dispatch({ type: "change_name", name: "ww" });
store.dispatch(changeNameAction("ww6"));
// store.dispatch({ type: "change_name", name: "dhs" });
store.dispatch(changeNameAction("dhs6"));
// 取消订阅
unsubscribe();
// 修改count
// store.dispatch({ type: "add_count", num: 10 });
store.dispatch(addCountAction(10));
                                      05动态生成action-action单独抽取.js
const store = require("./store/index-if判断");
const { changeNameAction, addCountAction } = require("./store/actionCreators");
const unsubscribe = store.subscribe(() => {
  // 只要派发action,就会执行
  console.log("订阅数据的变化:", store.getState());
});
// 修改store中的数据:必须通过action
// store.dispatch({ type: "change_name", name: "ww" });
store.dispatch(changeNameAction("cw"));
// store.dispatch({ type: "change_name", name: "dhs" });
store.dispatch(changeNameAction("wzm"));
// 取消订阅
// unsubscribe();
// 修改count
// store.dispatch({ type: "add_count", num: 10 });
store.dispatch(addCountAction(10));
                                                utils.js
const store = require("./store");
const { changeNameAction } = require("./store/actionCreators");
store.dispatch(changeNameAction("zm_ww"));
console.log("store.getState()=> ", store.getState());

react中使用redux

创建项目 create-react-app learn-react-redux

npm i redux

项目结构:

image.png 效果图: image.png 代码:

import React, { PureComponent } from "react";
import store from "../store";
import { addCountAction } from "../store/actionCreators";

export class Home extends PureComponent {
  constructor() {
    super();
    this.state = {
      count: store.getState().count,
    };
  }
  componentDidMount() {
    store.subscribe(() => {
      const state = store.getState();
      console.log("Home subscribe state=> ", state);
      this.setState({
        count: state.count,
      });
    });
  }
  addCount(num) {
    store.dispatch(addCountAction(num));
  }
  render() {
    const { count } = this.state;
    return (
      <div>
        <h2>Home count:{count}</h2>
        <div>
          <button onClick={(e) => this.addCount(1)}>+1</button>
          <button onClick={(e) => this.addCount(5)}>+5</button>
          <button onClick={(e) => this.addCount(10)}>+10</button>
        </div>
      </div>
    );
  }
}
export default Home;
import React, { PureComponent } from "react";
import store from "../store";
import { subCountAction } from "../store/actionCreators";

export class Profile extends PureComponent {
  constructor() {
    super();
    this.state = {
      count: store.getState().count,
    };
  }

  componentDidMount() {
    store.subscribe(() => {
      const state = store.getState();
      console.log("Profile subscribe state=> ", state);
      this.setState({
        count: state.count,
      });
    });
  }

  subCount(num) {
    store.dispatch(subCountAction(num));
  }

  render() {
    const { count } = this.state;
    return (
      <div>
        <h2>Profile count:{count}</h2>
        <div>
          <button onClick={(e) => this.subCount(1)}>-1</button>
          <button onClick={(e) => this.subCount(5)}>-5</button>
          <button onClick={(e) => this.subCount(10)}>-10</button>
        </div>
      </div>
    );
  }
}
export default Profile;
import * as actionTypes from "./constants";

export function addCountAction(count) {
  return {
    type: actionTypes.ADD_COUNT,
    count,
  };
}

export const subCountAction = (count) => ({
  type: actionTypes.SUB_COUNT,
  count,
});
export const ADD_COUNT = "add_count";
export const SUB_COUNT = "sub_count";
import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(reducer);
export default store;
import * as actionTypes from "./constants";

const initState = {
  count: 666,
};

function reducer(state = initState, action) {
  switch (action.type) {
    case actionTypes.ADD_COUNT:
      return { ...state, count: state.count + action.count };
    case actionTypes.SUB_COUNT:
      return { ...state, count: state.count - action.count };
    default:
      return state;
  }
}
export default reducer;
import React, { PureComponent } from "react";
import Home from "./pages/Home";
import Profile from "./pages/Profile";
import "./style.css";
import store from "./store";

export class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      count: store.getState().count,
    };
  }
  componentDidMount() {
    store.subscribe(() => {
      const state = store.getState();
      console.log("App subscribe state=> ", state);
      this.setState({
        count: state.count,
      });
    });
  }
  render() {
    const { count } = this.state;
    return (
      <div>
        <h2>App count:{count}</h2>
        <div className="panel">
          <div className="home">
            <Home />
          </div>
          <div className="profile">
            <Profile />
          </div>
        </div>
      </div>
    );
  }
}
export default App;
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  // <React.StrictMode>
  <App />
  // </React.StrictMode>
);
.panel {
  display: flex;
}
.panel .home {
  flex: 1;
  border: 2px solid aquamarine;
  padding: 20px;
}
.panel .profile {
  flex: 1;
  padding: 20px;
  border: 2px solid purple;
}

react-redux使用

npm i react-redux

image.png