const submitted = useSelector((state) => state.post.submitted)
在国家上面。我收到错误:
(参数)状态:unknown对象的类型为“unknown”。
这是如何解决的?
简单的slice + store:
import { createSlice } from '@reduxjs/toolkit'
export const postSlice = createSlice({
name: 'post',
initialState: {
shared: false,
submitted: false,
},
reducers: {
setShared: (state, action) => {
state.shared = action.payload
},
setSubmitted: (state, action) => {
state.submitted = action.payload
},
},
})
export const { setShared, setSubmitted } = postSlice.actions
export default postSlice.reducer
import { configureStore, combineReducers } from '@reduxjs/toolkit'
//import slice as reducer
import postReducer from './features/postSlice'
const rootReducer = combineReducers({
//combine all reducers
post: postReducer,
})
export const store = configureStore({
reducer: rootReducer,
})
我没有得到这种类型的错误的Javascript,虽然弹出在TS?如果需要的话,需要声明什么类型的类型?
3条答案
按热度按时间xkrw2x1b1#
您应该遵循TypeScript快速入门指南并设置正确类型的钩子:
xriantvc2#
useSelector
是泛型,不能确定state
是什么类型,所以默认为unknown
。你需要给予state一个与initialState
的形状匹配的类型注解,所以你需要把它从切片定义中分离出来。1.定义接口(如果愿意,也可以使用类型/类型别名)
1.类型转换
initialState
,或者使用一个中间类型变量(我认为这是可选的,但看一下文档中的示例表明这是可能的):1.向回调添加类型注解
kqlmhetl3#
const generalUserInfo = useSelector((state:return();
执行此操作:状态**:任何**