欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【React】19课 react组件使用redux小案例

程序员文章站 2022-07-03 17:37:54
...

小案例效果入下:

【React】19课 react组件使用redux小案例

我们来看一下文件的目录结构:

【React】19课 react组件使用redux小案例

redux文件内的index.js文件代码:

const add_Num = '增加一条数据';
const remove_Num = '删除一条数据';
/*
  state:数据原先的状态
  action:需要来进行改造的内容
    action.type 决定你要处理的类型
      进行判断:if,swich
*/ 
export function reducer(state=0,action){
  switch(action.type){
    case '增加一条数据':
      return state + 1
    case '删除一条数据':
      return state - 1
    default:
      return 0
  }
}

export function addNum(){
  return{
    type: add_Num
  }
}

export function removeNum(){
  return{
    type: remove_Num
  }
}

src文件内的index.js文件代码:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './redux/index'
import {
  reducer,
  addNum,
  removeNum,
} from './redux/index'; //导入redux文件
import { createStore } from 'redux';  //引入redux

console.log(reducer);
console.log(addNum);
console.log(removeNum);

//创建库
const store = createStore(reducer);

render();
function render(){
  ReactDOM.render(
    <App 
      store={store}
      add={addNum}
      remove={removeNum}
    />,
    document.getElementById('root')
  );
}

//监听到dispatch事件执行,后数据改变时就执行listener()
store.subscribe(render)

src文件内的App.js组件代码:

import React, { Component } from 'react'

export default class App extends Component {
  render() {
    const {store, add, remove} = this.props;
    return (
      <div>
        <h1>redux实践</h1>
        <h2>数据有{ store.getState() }</h2>
        
        <input 
          type="button"
          value={'增加'}
          onClick={
            ()=>{store.dispatch( add() ) }
          }
        />
        <input 
          type="button"
          value={'删除'}
          onClick={
            ()=>{store.dispatch( remove() ) }
          }
        />
      </div>
    )
  }
}

package.json配置文件代码如下:

{
  "name": "myapp1",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-router-dom": "^5.0.1",
    "react-scripts": "3.0.1",
    "redux": "^4.0.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}