vuejs和reactjs中,关于状态管理的替代【vuex/redux】

in React with 2 comments

请输入图片描述
我们在写前端项目时候,有时候不得不在组件中更新兄弟父亲姐妹的各种状态,
VUEJS的解决办法是vuex,reactjs是redux,
都是定义全局state, 通过action=>dispatch来更新状态,并且通过持久化插件写入session 或者local stroge中,

随着项目的复杂,vuex|redux越来越复杂,已经违背的设计者的初衷,
尤其是reactjs: 尽量不用redux就坚决别用。在react hooks中就体现了这一点,
那么怎么脱离这个复杂的state=>action=>dispatch逻辑呢?
这里推荐一个插件:lowdb.
项目地址:https://github.com/typicode/lowdb

在项目中创建utils/db.js

import low from 'lowdb'
import LocalStorage from 'lowdb/adapters/LocalStorage'

const adapter = new LocalStorage('your appaction storage name')
const db = low(adapter)

const store = { token: '', username: '', user: {} }
db.defaults(store).write()

export default db

vuejs中,在App.vue项目中初始化db:

<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>

import db from './libs/db'

export default {
  name: 'App',
  data () {
    return {
      db: db
    }
  }
}
</script>

在reactjs中,创建一个db的provider组件:

import react, {useEffect} from 'React'
import db from './libs/db'
const ProviderForDB = (props)=>{
     useEffect(()=>{
         const store = { token: '', username: '', user: {} }
         db.defaults(store).write()
     }, [])
     return <div>{props.children}</div>
}
export defualt ProviderForDB;

使用方法:

db.get('posts')
  .push({ id: 1, title: 'lowdb is awesome'})
  .write()

// Set a user using Lodash shorthand syntax
db.set('user.name', 'typicode')
  .write()
  
// Increment count
db.update('count', n => n + 1)
  .write()

具体的案例:
登录:

import db from './libs/db'
this.login({ username: this.username, password: this.password }).then(res => {
   db.set('token', res.data.token).set('username', res.data.username).set('user', res.data.user).write()
})

注销:

import db from './libs/db'
this.login({ username: this.username, password: this.password }).then(res => {
   db.set('token', '').set('username', '').set('user', {}).write()
})

通过db的方法来实现状态的更新,并且持久化。

Comments are closed.