반응-축소 사용선택자 형식 상태 유형
나는 그것을 사용하고 있다.useSelector(state => state.SLICE_NAME)
React-Redex에서 후크를 사용하지만 후크를 정의하는 데 어려움이 있음state
매개 변수기본적으로 다음과 같이 설정되어 있다.unknown
그래서 내가 돌아오려고 할 때 오류가 생긴다.state.SLICE_NAME
(Error: Object is of type 'unknown'
).
다음을 정의하려면state
별도의 상태 유형을 수동으로 생성하지 않고 새로운 상태 정의가 생성될 때마다 추가하시겠습니까?
나는 상태를 다음과 같이 정의하려고 노력했다.typeof store
하지만 그건 효과가 없어
설명에 도움이 되는 몇 가지 코드:
// navDrawer.ts
import { createSlice } from "redux-starter-kit";
// navDrawer initial state
export interface NavDrawerInitialState {
open: boolean;
}
const navDrawerInitialState: NavDrawerInitialState = {
open: false
};
// Create state slice
const { actions, reducer } = createSlice({
slice: "navDrawer",
initialState: navDrawerInitialState,
reducers: {
open: (state: NavDrawerInitialState) => {
state.open = true;
},
close: (state: NavDrawerInitialState) => {
state.open = false;
}
}
});
export const navDrawerActions = actions;
export default reducer;
// reducers.ts
import navDrawer from "./navDrawer";
const reducers = {
navDrawer
};
export default reducers;
// store.ts
import { configureStore } from "redux-starter-kit";
import reducer from "./reducers";
const store = configureStore({
reducer
});
export default store;
// Page.tsx
import React, { FC } from "react";
import { Provider } from "react-redux";
import store from "./store";
import ChildComponent from "./ChildComponent";
const StateProvider: FC = () => {
return <Provider store={store}><ChildComponent /></Provider>;
};
export default StateProvider;
// ChildComponent.tsx
import React, { FC } from "react";
import { useSelector } from "react-redux";
const ChildComponent: FC = () => {
const navDrawerState = useSelector(state => state.navDrawer); // ERROR OCCURS HERE. "state" is defined as 'unknown' so "state.navDrawer" throws an error.
return <div>Text</div>
}
편집: 다음에 대한 유형 정의가configureStore()
상태를 첫 번째 일반 유형으로 포함.아래 스크린샷을 참조하십시오.첫 번째 일반 값을 가져올 수 있는 경우EnhancedStore
그럼 내가 그걸 이용해서 상태를 정의할 수 있을 거야내가 이것을 Typecript에서 할 수 있는 방법이 있을까?
이것이 정답은 아닐지 모르지만 나는 이렇게 사용한다.
const isLoggedIn = useSelector<IRootState, boolean>(state => state.user.loggedIn);
편집: 또는 더 짧고 깨끗한 피터의 답변을 사용하십시오.
const isLoggedIn = useSelector((state: IRootState) => state.user.loggedIn);
사용자 정의 입력된 용도를 만들 수 있음선택자:
import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux'
import { RootState } from 'app/redux/store'
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector
어디에RootState
스토어의 유형이며, 일반적으로 다음과 같이 정의된다.
export type RootState = ReturnType<typeof rootReducer>
설치하는 것을 잊지 마십시오.@types/react-redux
.
다음은 환원 문서(더 많거나 더 적음)의 제안사항:
import { RootState } from 'app/redux/store';
const isLoggedIn = useSelector(state: RootState => state.user.loggedIn);
@Federkun의 대답보다 훨씬 간단하다는 것이 장점이다.@alextrastero의 답변에 비해 유리한 점은 isLogged를 지정할 필요가 없다는 점이다.인의 입력은 수동으로 입력하십시오.
만들다
config.d.ts
사용자 지정 상태 정의
import 'react-redux'; import { ApplicationState } from '@store/index'; declare module 'react-redux' { interface DefaultRootState extends ApplicationState {} }
Reducx 문서에 따라 store.tsx 파일에서 상태를 RootState로 내보내기
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
그런 다음 구성 요소에서 다음 이름으로 사용
const navDrawerOpen = useSelector((state:RootState) => state.navDrawer.open);
Thanks to @Иван Яковлев, I've finally achieved my perfect solution :d
import { useSelector } from 'react-redux'
import configureStore from '../configureStore'
export const { store } = configureStore()
// We can use RootState type in every file in project
declare global {
type RootState = ReturnType<typeof store.getState>
}
// Thanks to that you will have ability to use useSelector hook with state value
declare module 'react-redux' {
interface DefaultRootState extends RootState { }
}
const profile = useSelector(state => state.profile) // Profile is correctly typed
유형작업 사용.그것은 정말로 당신의 삶을 편하게 해준다.
npm install --save typesafe-actions
- Reducer 또는 rootReducer 파일로 이동 및
import { StateType } from 'typesafe-actions';
- 환원기 기능을 기록하십시오.
export type Store = StateType<typeof yourReducer>;
그러면
- 사용할 ts 파일로 이동하여
import { useSelector } from 'react-redux';
import {Store} from 'your-reducer-or-wherever-file'
- 구성 요소 내부:
const store = useSelector((store: Store) => { return {students: store.manager.students} });
용도에 있는 환원기에서 내보낸 스토어 유형 선택기 후크(사용에 필요한 용도는 스토어 유형이며, 방금 사용한 것처럼 유형 실행으로 쉽게 구할 수 있음)를 확인하십시오.또한 내가 사용하고자 하는 모든 상태가 포함된 개체를 어떻게 반환했는지도 주의하십시오.이 시점에서 창의력을 얻을 수 있어, 그건 중요하지 않아.10행의 상점 변수는 모든 상태를 가지고 있으며, 원한다면 구조를 파괴하는 것도 좋다.https://www.npmjs.com/package/typesafe-actions에서 유형별 작업에 대한 자세한 내용을 읽어 보십시오.
import React from 'react'
import { useSelector } from 'react-redux'
type RootState = {
auth: {
login: string
isAuth: boolean
}
}
const State: RootState = {
auth: {
login: ''
isAuth: false
}
}
export function useSelectorTyped<T>(fn: (state: RootState) => T): T {
return useSelector(fn)
}
const LoginForm = () => {
const { login, loginError } = useSelectorTyped(state => state.auth)
return null
}
'react-remensx' 번들이 제공하는 유형이 있다.
import { RootStateOrAny} from "react-redux";
const recentActivityResponse = useSelector(
(state: RootStateOrAny) => state.dashboard.recentActivityResponse
);
방금 코드에서 이 작은 조각을 찾았어
/**
* This interface can be augmented by users to add default types for the root state when
* using `react-redux`.
* Use module augmentation to append your own type definition in a your_custom_type.d.ts file.
* https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
// tslint:disable-next-line:no-empty-interface
export interface DefaultRootState {}
그냥 아무거나 써도 돼.다른 해결책일 뿐이야.
나는 이것을 철저히 이해하는 가장 좋은 방법은 Redex 문서 그 자체라고 생각한다.
https://react-redux.js.org/using-react-redux/usage-with-typescript
그들은 말한다.
타이핑된 후크 정의 루트 상태 및 AppDispatch 유형을 각 구성 요소로 가져올 수 있지만 응용 프로그램에서 사용할 수 있도록 미리 타이핑된 useDispatch 및 useSelector 후크를 만드는 것이 좋다.이것은 다음과 같은 몇 가지 이유로 중요하다.사용 Selector의 경우 입력할 필요가 없어짐(상태:루트 상태) 매번 사용Dispatch의 경우 기본 디스패치 유형은 thunk 또는 다른 미들웨어에 대해 알지 못한다.툰크를 올바르게 발송하기 위해서는 툰크 미들웨어 타입이 포함된 스토어에서 특정 맞춤형 앱디스패치 타입을 사용하고, useDispatch와 함께 사용해야 한다.사전 형식 사용Dispatch 후크를 추가하면 필요한 곳에 AppDispatch를 가져오는 것을 잊어버리지 않게 된다.
따라서 아래 내용은 항상 선택기나 디스패치를 계속 입력할 필요가 없도록 해야 한다.
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
참조URL: https://stackoverflow.com/questions/57472105/react-redux-useselector-typescript-type-for-state
'programing' 카테고리의 다른 글
Nuxtjs는 '분할을 위해 / 를 많이 던지는 것은 더 이상 사용되지 않으며 다트 사스 2.0.0에서 제거될 것이다.` (0) | 2022.03.11 |
---|---|
어떻게 분단을 부동의 지점으로 강제할 수 있을까?0으로 반올림하는 중인가? (0) | 2022.03.11 |
Vuetify에서 v-card 구성 요소의 중앙에 콘텐츠를 맞추는 방법 (0) | 2022.03.11 |
반응을 사용하여 개체 배열을 다른 구성 요소로 전달 (0) | 2022.03.11 |
history hook in jest를 조롱하는 방법? (0) | 2022.03.11 |