[英]Object is of type 'unknown'.ts
I'm trying TypeScript by creating a Redux store with Redux Tooklit.我正在通过使用 Redux Toolit 创建一个 Redux 商店来尝试 TypeScript。
Here is my redux.js
file :这是我的
redux.js
文件:
import { configureStore, createSlice } from "@reduxjs/toolkit";
const testSlice = createSlice({
name: "test",
initialState: [],
reducers: {
callApi: (state, action) => {
const getData = {
type: "test/getData",
data: action.payload
};
state.push(getData);
}
}
});
export const store = configureStore({
reducer: {
test: testSlice.reducer
}
})
Here is my index.tsx
file :这是我的
index.tsx
文件:
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import App from './App';
import './index.css';
import { store } from './redux'
const container = document.getElementById('root')!;
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
And finaly, my component Login.tsx
file :最后,我的组件
Login.tsx
文件:
[...]
import { useSelector } from 'react-redux';
[...]
const test = useSelector((state) => state.test);
[...]
In Login.tsx
, VSCode underline state
in red, and says :在
Login.tsx
中,VSCode 用红色下划线state
,并说:
Object is of type 'unknown'
I tried to tell TypeScript what kind of type to expect like this : const test = useSelector((state: Object) => state.test);
我试图告诉 TypeScript 期望什么样的类型:
const test = useSelector((state: Object) => state.test);
but I get an error saying that test
is not an object.但我得到一个错误,说
test
不是一个对象。 Same try with Array.同样尝试使用 Array。
I'm a bit lost.我有点失落。 Can anyone explain me where is my mistake and how to fix this ?
谁能解释我的错误在哪里以及如何解决这个问题?
Thank you very much.非常感谢。
You can add this line od code to redux.js file您可以将此行 od 代码添加到 redux.js 文件
export type RootState = ReturnType<typeof store.getState>;
Then you can use this type in useSelector hook然后你可以在 useSelector 钩子中使用这个类型
const test = useSelector((state: RootState) => state.test);
As you are correctly thinking you need to give a type to the state so that it doesn't get the default unknown type.正如您正确认为的那样,您需要为状态提供一个类型,以便它不会获得默认的未知类型。 However, instead of using the Object type you should use a custom one that correctly represents your whole state.
但是,您应该使用正确代表整个状态的自定义类型,而不是使用Object类型。 You can create one by adding this in your
redux.js
file:你可以通过在你的
redux.js
文件中添加这个来创建一个:
export type RootState = ReturnType<typeof store.getState>
Then, from your Login.tsx
file you can do:然后,从您的
Login.tsx
文件中,您可以执行以下操作:
const test = useSelector((state: RootState) => state.test);
More official docs here: https://redux-toolkit.js.org/tutorials/quick-start#add-slice-reducers-to-the-store更多官方文档: https ://redux-toolkit.js.org/tutorials/quick-start#add-slice-reducers-to-the-store
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.