今天重构一下代码,就不做新功能了
首先我们把authSlice
改为userSlice
,因为是登录和退出,用用户来表示比较好,因为前面一些代码有改动,所以我们还是删除store/slices/authSlice.js
,然后新建store/slices/userSlice.js
js
'use client'
import { createSlice } from '@reduxjs/toolkit'
const token = window.localStorage.getItem('token') || ''
const initialState = { userInfo, token }
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
userLogout: state => {
localStorage.removeItem('token')
state.token = ''
},
userLogin: (state, action) => {
localStorage.setItem('token', action.payload)
state.token = action.payload
},
userInfo: (state, action) => {
state.userInfo = action.payload
},
},
})
export const { userLogout, userLogin, userInfo } = userSlice.actions
export default userSlice.reducer
然后在store/index.js
中导出
js
import { configureStore } from '@reduxjs/toolkit'
import fetchApi from '@/store/slices/fetchApiSlice'
import userReducer from '@/store/slices/userSlice'
import cartSlice from '@/store/slices/cartSlice'
export const store = configureStore({
reducer: {
user: userReducer,
cart: cartSlice,
[fetchApi.reducerPath]: fetchApi.reducer,
},
middleware: getDefaultMiddleware => getDefaultMiddleware().concat(fetchApi.middleware),
})
hooks
实现一个useVerify
用来校验token,新建hooks/useVerify.js
js
import { useSelector } from 'react-redux'
import jwt from 'jsonwebtoken'
export default function useVerify() {
const { token } = useSelector(state => state.user)
let status
if (!token) return false
jwt.verify(token, process.env.NEXT_PUBLIC_ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) status = false
if (decoded) status = true
})
if (status) return true
else return false
}
修改components/Layouts/ProfileLayout.tsx
tsx
'use client'
import { useRouter } from 'next/navigation'
import { useSelector } from 'react-redux'
import { ClientLayout, ProfileAside } from '@/components'
import useVerify from '@/hooks/useVerify'
export default function ProfileLayout({ children }: any) {
const isVerify = useVerify()
const router = useRouter()
const { user } = useSelector((state: any) => state.user)
if (!isVerify) {
router.push('/')
} else {
return (
<>
<ClientLayout>
<div className="lg:flex lg:gap-x-4 lg:px-3 lg:container lg:max-w-7xl">
<div className="hidden lg:block">
<ProfileAside user={user} />
</div>
<div className="py-4 lg:py-8 lg:border lg:border-gray-300 flex-1 lg:rounded-md lg:mt-6 h-fit">
{children}
</div>
</div>
</ClientLayout>
</>
)
}
}
剩余其他的都是进行了js
变成ts