我在Ionic中使用了Typescript以及React钩子,因此我在其中添加了errorReducer,用于处理用户从服务器获取的错误,以防万一出现问题。
这是我的下面的代码
动作
import { ERROR_OCCURED } from "./types";
export const errorActions = () => async (dispatch: any) => {
console.log('err action triggered')
dispatch({
type: ERROR_OCCURED
});
};
减速器
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;
然后在我的打字稿组件中
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;
等等
console.log(state.error)
最初我得到{}
,但是在状态更新后我得到了
{isauth:true}
但是如果我尝试通过useSelector访问此布尔值,则
console.log(state.error.isauth)
我收到指出的打字稿错误
类型'{}'不存在属性'isauth'。
或者简单地说,我如何告诉TypeScript最初以某种方式跳过空object{}
而不检查其键值对,因为更新状态会花费一些时间
答案 0 :(得分:1)
我建议保持一致,而不要传递空的错误对象{}。
错误通过:
{ isauth: false; }
我相信Typescript仅用于此目的,以便让您在早期阶段就知道自己的错误。这样,每个查看您的组件的人都会知道,您将提取(持有)的数据!