[英]Can't access redux state object's key in TypeScript
I am using typescript in Ionic along with React hooks, so I was adding my errorReducer in it which handles the error user gets from server in case anything goes wrong.我在 Ionic 中使用 typescript 和 React 钩子,所以我在其中添加了我的 errorReducer,它可以处理用户从服务器获取的错误,以防出现任何问题。
Here is my code below下面是我的代码
Action行动
import { ERROR_OCCURED } from "./types";
export const errorActions = () => async (dispatch: any) => {
console.log('err action triggered')
dispatch({
type: ERROR_OCCURED
});
};
Reducer减速器
import { ERROR_OCCURED } from "../actions/types";
function fetchRedcuer(state = {}, action: any) {
switch (action.type) {
case ERROR_OCCURED:
return {
...state,
isauth:true
};
default:
return state;
}
}
export default fetchRedcuer;
then in my typescript component然后在我的打字稿组件中
import { useSelector, useDispatch } from "react-redux";
import React, { useState, useEffect } from "react";
import { userRegisterAction } from "../../src/redux/actions/user";
import { RootState } from "../redux/reducers";
type IUser = {
error: { [isauth: string]: boolean };
};
const Signup: React.FC<IUser> = (props) => {
const [state, setState] = useState<IUser>({
error:{}
});
const dispatch = useDispatch();
const error = useSelector((state: RootState) => {
console.log(state.error); //here i get access to my state that is inside error reducer and also here i get error when i try to access boolean value
return { error: state.error };
});
console.log(error.error);
return (
<div>
</div>
);
};
export default Signup;
so on很快
console.log(state.error)
控制台日志(状态。错误)
initally I get {}
but then after the state has been updated i get最初我得到
{}
但在状态更新后我得到
{isauth: true}
{isauth:真实}
but then if i try to access this boolean value in useSelector by但是如果我尝试通过以下方式访问 useSelector 中的这个布尔值
console.log(state.error.isauth)
控制台日志(状态。错误。isauth)
I get the typescript error which states我收到了说明的打字稿错误
Property 'isauth' does not exist on type '{}'.
类型“{}”上不存在属性“isauth”。
OR in simple words how do I tell TypeScript to somehow initially skip the empty object{}
and not check for its key value pairs as updating state takes a little time或者简单地说,我如何告诉 TypeScript 以某种方式最初跳过空
object{}
而不检查其键值对,因为更新状态需要一点时间
I recommend to stay consistent and instead of passing empty error object {}.我建议保持一致,而不是传递空的错误对象 {}。
In error pass:在错误传递中:
{ isauth: false; }
I believe Typescript is for that purpose only, to let you know your mistakes at early stage's.我相信 Typescript 只是为了这个目的,让你在早期阶段就知道你的错误。 So everyone who looks at your component will know, the data you will be extracting(holding)!
因此,每个查看您的组件的人都会知道,您将提取(持有)的数据!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.