1.0.4 • Published 9 months ago

soul-react-redux v1.0.4

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

安装soul-react-redux

npm i -S soul-react-redux

在项目中使用

import { createStore } from "soul-react-redux"

//创建命名为app的状态管理模块
const app = {
    index:1
}

//创建命名为task的状态管理模块
const task = {
    count:100
}

const root_store = {
    task,
    app
}


//每创建一个状态管理模块,都会同时生成一个状态管理模块拼接_unique的一个变量返回,如app_unique,task_unique等等,可以使用这个唯一值去更新对应的状态管理模块
export const {
    store,
    app_unique,
    task_unique,
} = createStore(root_store)

在根文件中引入

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux'
import { store } from "./store";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Provider store={ store }>
        <App />
    </Provider>
);

reportWebVitals();

在函数App组件中使用

import { useSelector, useDispatch } from 'react-redux'
import { app_unique } from "./store";
import Demo from "./Demo";

const App = () => {

  const app = useSelector((state) => {
    return state.app
  })

  const task = useSelector((state) => {
    return state.task
  })

  const dispatch = useDispatch()

  const handleAdd = () => {
    const index = app.index + 1
    
    // 更新app状态管理模块的值,此处的更新逻辑是{ ...old_state,...new_state }
    dispatch({ type: app_unique,data:{ index } }) 
  }

  return <div className="App">
    <button onClick={ handleAdd }>
      测试
    </button>
    <div>
      { app.index }
    </div>
    <div>
      { task.count }
    </div>
    <Demo></Demo>
  </div>
}

export default App;

在类组件Demo中使用

import React, {Component} from 'react';
import { store, task_unique} from "./store";

class Demo extends Component {
    constructor(props) {
        super(props);
        this.dispatch = null
        this.app = {}
        this.task = {}
        this.getStoreState()
        const { subscribe } = store
        subscribe(()=>{
            this.getStoreState()
        })
    }

    getStoreState(){
        this.dispatch = store.dispatch
        const { app,task } = store.getState()
        this.app = app
        this.task = task
    }

    handleAdd(){
        const count = this.task.count + 10
        store.dispatch({ type: task_unique,data:{ count } })
    }

    render() {
        return (
            <div>
                <button onClick={ ()=>{ this.handleAdd() } }> 添加 </button>
                <div>{ this.app.index }</div>
                <div>{ this.task.count }</div>
            </div>
        );
    }
}

export default Demo
1.0.4

9 months ago

1.0.3

9 months ago

1.0.2

9 months ago

1.0.1

9 months ago