在react中加载时,如何处理Typescript类型的本地状态变量



我最近开始处理一个使用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获取之前,我实际上没有这个值。在这种情况下,我将在MyComponentInputComponent中得到类型HelloWorld与类型undefined不兼容的Typescript错误。

如何将currentFood状态变量初始化为一个组件链,在该组件链中,您必须处处支持类型undefined?这可能是吗

MyComponent中,可以将currentFoo定义为HelloWorldTypeundefined,在InputComponentPropType中,可以标记currentFoo属性为可选属性,在设置输入字段的namevalue时,请进行检查。如果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: "" });

相关内容

  • 没有找到相关文章

最新更新