话不多说,直接上代码
store的文件
import { create } from "zustand";
//真的好用,比vuex还快
interface Bear{
num:number;
[k:string]:any
}
//注意addnum是页面调用方法传过来的值
const useStore = create<Bear>((set)=>({
num:12,
addnum: (addnum : number) => set(state => ({ num: (state.num + Number(addnum)) })),
subtractnum: () => set(state => ({ num: state.num - 1 })),
}))
export default useStore
页面调用的文件
import React, { useRef } from 'react'
import { Button, Space } from 'antd';
import useStore from '../../store/Index';
export default function RegisterView() {
const mytext = useRef<HTMLInputElement | null>(null);
const num = useStore((state) =>state.num)
const adds = useStore((state) =>state.addnum)
const add = ()=>{
adds(mytext.current?.value)
}
return (
<div>
<div>RegisterView</div>
<input ref={mytext}></input>
<div>{num}</div>
<Button type="primary" onClick={add}>Primary Button</Button>
</div>
)
}
结果