【发布时间】:2018-10-06 18:51:39
【问题描述】:
我正在使用 API 创建一个 React 360 应用程序来获取数据,然后将其显示在面板上。下面我有以下代码:
export class CryptoControlInformation extends React.Component {
state = {
details: {
description: '',
links: [],
}
};
componentDidMount() {
const CRYPTO_CONTROL_PATH = 'https://cryptocontrol.io/api/v1/public/details/coin/bitcoin?key=some_key';
fetch(CRYPTO_CONTROL_PATH)
.then(response => response.json())
.then(data => {this.setState({
details: {
description: data["description"],
links: [...this.state.details.links, ...data["links"] ]
}})
})
}
render() {
let links = this.state.details.links;
##################################
console.log(links[0])
{_id: "5b41d21fa8a741cf4187ec60", type: "reddit", name: "r/Bitcoin Reddit", link: "https://reddit.com/r/Bitcoin/"}
####################################
####################################
// Why is this returning undefined?
console.log(links[0]["name"]);
####################################
return (
<View>
<View style={styles.rightHeader}>
<Text style={{fontSize: 40}}>Information</Text>
</View>
<View>
<Text>{this.state.details.description}</Text>
</View>
<View>
<Text>{this.state.details.description}</Text>
</View>
</View>
)
}
}
我无法获取对象内部的信息,我不明白为什么。我知道信息在那里。我可以 console.log 完整地记录对象,但各个部分是未定义的。我究竟做错了什么?我在反应中注意到状态总是必须明确详细。
例如,我发现我不能这样做:
export class Square extends React.Component {
state = {
info: undefined
};
componentDidMount() {
// grab information (pseudocode)
this.setState{info: data}
}
}
我必须实际绘制出令人讨厌的数据:
export class Square extends React.Component {
state = {
info: {
color: '',
height: '',
width: '',
}
};
componentDidMount() {
// grab information (pseudocode)
this.setState{info: {
color: data['red'],
heigth: data['height'],
width: data['width']
}
}
}
}
我认为这与我的问题有关。我在正确的轨道上吗?
【问题讨论】:
-
您不应该在设置新的状态值时访问
this.state值。在使用之前尝试使用之前的状态值将其设置为新状态this.setState( prevState => {{details: { description: data["description"], links: [...prevState.details.links, ...data["links"] ] }}})@Dan Rubio
标签: reactjs