react V6使用store存取/显示

功能背景

最近学了一点react的东西,以前以为就用vue走天下了,现在越来越卷了,不多学习不行了,后来还用过uniapp,原生weixin小程序比较少,原生js的公众号h5也写过一些,jq是很多年前用的了,最近也看了点flutter的东西,但是感觉flutter对于他的插件库维护的并不是很好,比如说三年前的项目,现在启动不了,可能会因为某些插件已经停止维护,或者更新语法,会跟现在的dart版本、flutter、java版本出现不适应的情况,很恶心。言归正传,这里简单小记一下react的store的使用

实际效果

登录的时候存了用户信息,然后在页面进行读取显示

实现代码

注意:以下代码不全,只展示了部分关键代码,需要自行调整,方可使用
store/index.js

// 把所有的模块做统一处理
// 导出一个统一的方法 useStore
import React from "react"
import UserStore from "./user.Store"

import { configure } from "mobx"
configure({
  enforceActions: "never",
})


class RootStore {
  constructor() {
    this.userStore = new UserStore()
    // ...
  }
}

// 实例化根
// 导出useStore context
const rootStore = new RootStore()
const context = React.createContext(rootStore)

const useStore = () => React.useContext(context)

export { useStore }

store/user.store.js

import { makeAutoObservable } from 'mobx'
import { http } from '@/utils'

class UserStore {
  userInfo = {}
  userDesc = ''
  constructor() {
    makeAutoObservable(this)
  }
  getUserInfo = async () => {
    // 调用接口获取数据
    const res = {name:"123",id:22}
    this.userInfo = res.data
    this.userDesc = '个人描述信息xxxx'
  }
}

export default UserStore

import { useStore } from '@/store'
const { userStore} = useStore()
useEffect(() => {
    userStore.getUserInfo()
  }, [userStore])

import { useStore } from '@/store'
//读取store中的信息
  const { userStore } = useStore()
useEffect(() => {
    console.log('fsdhh 的书法绘画的',userStore)
  }, [userStore])
  <p>userDesc: {userStore.userDesc}</p>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_小郑有点困了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值