全部, 我在主题新阵营+打字稿。 在我的示例代码中,我得到json对象,并将要在控制台上打印一个属性。来自服务器的数据已成功发送。但是,企图使我收到消息输出“的属性‘相册’类型不存在‘从未[]’”,但所有类型的定义。我哪里错了?我应该某种方式初始化的状态“画廊”?
import React, { Component, Props } from 'react';
import axios from 'axios';
const API = 'http://www.mydomain/testapi/';
const DEFAULT_QUERY = 'test.php';
type Image = {
id: number,
name: string,
title: string,
date: string,
size: number
}
type Album = {
id: number,
name: string,
path: string,
images: Image[]
}
interface State {
jsonFromServer: string,
isLoading: boolean,
errorMsg: string,
buttonClicked: boolean,
gallery:Album[]
}
class App extends React.Component {
state = {
isLoading: false,
errorMsg: '',
buttonClicked: false,
jsonFromServer: "",
gallery:[]
}
getInfo() {
this.setState({ isLoading: true, buttonClicked: true });
axios.get(API + DEFAULT_QUERY)
.then(result => this.setState({
gallery: result.data.gallery,
isLoading: false,
jsonFromServer: result.data
}))
.catch(error => this.setState({
errorMsg: error.message,
isLoading: false
}));
}
render() {
.....
if (this.state.buttonClicked) {
this.state.galerie.length > 0 ? console.log('=>', this.state.gallery.album.id) : '';
}
......
}
}
export default App;
答案 0 :(得分:2)
您定义了private static final String REGEX_FILTER_KEY = "[:]+((?=\\[)\\[[^]]*\\]|(?=\\{)\\{[^\\}]*\\}|\\\"[^\"]*\\\"|(\\d+(\\.\\d+)?))";
List<String> redactKeys = Collections.unmodifiableList(Arrays.asList("username", "password", "userId"));
private String redact(@NonNull String responseString) {
for (String key : redactingKeys) {
Matcher matcher = Pattern.compile(String.format("\"%s\"%s", key, REGEX_FILTER_KEY)).matcher(responseString);
if (matcher.find() && matcher.group(1) != null) {
responseString = responseString.replace(matcher.group(1), "**********");
}
}
return responseString;
}
,但未指定其类型。因此,打字稿将基于初始化来推断state
的类型。由于state
是一个数组,但没有元素,因此可以推断的最佳和最安全的类型打字稿是galerie
解决方案是注释never[]
成员:
state
答案 1 :(得分:0)
您的图库是一个数组,并且您试图像对象一样对其进行访问。请尝试以下渲染方法:
render() {
.....
if (this.state.buttonClicked) {
this.state.galerie.length > 0 ? console.log('=>', this.state.gallery!.album.id) : ''; //it should work now
}
......
}