嘿需要一些有关反应打字稿的帮助
这里我定义了一个变量,
data
const [data, setData] = useState({
files: [],
processed_files: Number,
URL: String,
});
记录
data
工作正常:
(3) [{…}, {…}, {…}]
0: {files: Array(2)}
1: {processed_files: 0}
2: {url: 'f179d744-cdfb-4546-b756-afb6d5daaeff'}
length:3
[[Prototype]]:Array(0)
我尝试以这种方式使用setData:
socket.on("send_data", function (...response: any) {
setData(response)
});
但是进一步记录字典中的键表明它是未定义的:
useEffect(() => {
console.log(data); //this works fine (image uploaded)
console.log(data.files); //undefined
console.log(data.processed_files); //undefined
console.log(data.url); //undefined
}, [data]);
然后我尝试这个,但它会导致错误
socket.on("send_data", function (...response: any) {
setData({files : response[0], processed_files : 0 as Number, URL : "" as String});
});
Type 'Number' is missing the following properties from type 'NumberConstructor': prototype, MAX_VALUE, MIN_VALUE, NaN, and 11 more. ts(2740)
Type 'String' is missing the following properties from type 'StringConstructor': prototype, fromCharCode, fromCodePoint, raw ts(2739)
我该怎么办?
使用 原始类型 (
string
, number
) 而不是内置类型 (String
, Number
)。
此外,您应该在
useState
中定义类型,如下所示:
const [data, setData] = useState<{
files: [];
processed_files: number;
URL: string;
} | null>(null);
socket.on("send_data", function (...response: any) {
setData({ files: response[0], processed_files: 0, URL: "" });
});