react 中使用redux的createStore 创建公用变量

import { createStore } from 'redux'
import { useState } from 'react';

export const store = createStore(addTodo, 0);

function addTodo(state = 0, { type, num = 1 }) {
    switch (type) {
        case "add":
            return state + num;
        case "update":
            return num;
        default:
            return state;
    }
}


export const useStore = function (store){

  const [stateValue, setStateValue] = useState(store.getState())

  //变更订阅
  store.subscribe(function(){
    setStateValue(store.getState());
  })

  const set = function(val){
    store.dispatch({ type: 'update', num: val });
  }

  return [stateValue, set];
}
import logo from './logo.svg';
import './App.css';

import { store, useStore } from './redux/index'


export const Dom1 = function(){
  const [s] = useStore(store);
  return <div> {s} </div>
}

function App() {

  const [s, ss] = useStore(store);

  const changeStore = function (){
    ss( s + 1 );
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <p onClick={ changeStore }>{ s }</p>

        <Dom1></Dom1>

      </header>
    </div>
  );
}

export default App;

 

posted @ 2023-02-02 17:43  blurs  阅读(141)  评论(0编辑  收藏  举报