我最近开始处理一个使用Typescript的React项目,我遇到了一个特殊的问题,我不知道如何在Typescript中处理它。这在react项目中很常见,我相信有办法解决它,但还没有找到有用的文档。
import * as React from "react";
import { useDispatch, useSelector } from "react-redux-consumer";
import { loadFoo } from "reduxActions/action";
type FooType = {
hello: HelloWorldType;
world: HelloWorldType;
}
type HelloWorldType = {
name: string;
value: string;
}
const MyComponent = () => {
// On load foo value hasn't been loaded yet. Initialize it to empty
const [currentFoo, setCurrentFoo] = React.useState<HelloWorldType>();
const foo = useSelector(state => state.foo);
const dispatch = useDispatch();
React.useEffect(() => {
dispatch(loadFoo());
}, [loadFoo]);
return (
<div>
<InputComponent currentFoo={currentFoo} setCurrentFoo={setCurrentFoo}/>
</div>
);
}
export type setCurrentFoo = React.Dispatch<
React.SetStateAction<HelloWorldType>
>;
type InputComponentPropType = {
currentFoo: HelloWorldType;
setCurrentFoo: setCurrentFoo;
}
const InputComponent = (props: InputComponentPropType) => {
const {currentFoo, setCurrentFoo} = props;
return (
<input
type="checkbox"
id="hello"
name={currentFoo.name}
value={currentFoo.value}
onChange={e => {
setCurrentFoo(currentFoo)
}
/>
);
}
在上面的代码示例中,我的currentFoo
变量需要是HelloWorld
类型,但我的问题是,在从redux状态加载或从api获取之前,我实际上没有这个值。在这种情况下,我将在MyComponent
和InputComponent
中得到类型HelloWorld
与类型undefined
不兼容的Typescript错误。
如何将currentFood
状态变量初始化为一个组件链,在该组件链中,您必须处处支持类型undefined
?这可能是吗
在MyComponent
中,可以将currentFoo
定义为HelloWorldType
或undefined
,在InputComponentPropType
中,可以标记currentFoo
属性为可选属性,在设置输入字段的name
或value
时,请进行检查。如果currentFoo
不存在,则将其指定为某个默认值。我已经将它分配给下面的空字符串,但您可以用任何值来分配它。
import * as React from "react";
import { useDispatch, useSelector } from "react-redux-consumer";
import { loadFoo } from "reduxActions/action";
type FooType = {
hello: HelloWorldType;
world: HelloWorldType;
}
type HelloWorldType = {
name: string;
value: string;
}
const MyComponent = () => {
// On load foo value hasn't been loaded yet. Initialize it to empty
const [currentFoo, setCurrentFoo] = React.useState<HelloWorldType|undefined>();
const foo = useSelector(state => state.foo);
const dispatch = useDispatch();
React.useEffect(() => {
dispatch(loadFoo());
}, [loadFoo]);
return (
<div>
<InputComponent currentFoo={currentFoo} setCurrentFoo={setCurrentFoo}/>
</div>
);
}
export type setCurrentFoo = React.Dispatch<
React.SetStateAction<HelloWorldType>
>;
type InputComponentPropType = {
currentFoo?: HelloWorldType; // '?' makes this property/field optional
setCurrentFoo: setCurrentFoo;
}
const InputComponent = (props: InputComponentPropType) => {
const {currentFoo, setCurrentFoo} = props;
return (
<input
type="checkbox"
id="hello"
name={currentFoo?.name || ""}
value={currentFoo?.value || ""}
onChange={e => {
setCurrentFoo(currentFoo)
}
/>
);
}
或
一个简单得多的方法是用伪值初始化MyComponent
中的currentFoo
const [currentFoo, setCurrentFoo] = React.useState<HelloWorldType>({ name: "", value: "" });