我无法让数据脱离状态并在其上应用 map 功能。我不断得到 p>
TypeError: Cannot read property 'financials' of null.
axios 获取以下对象,{symbol: "AAPL", financials: Array(4)},这就是我使用 this.state.financials.financials 的原因
class Fundamentals extends Component {
state = {
financials: null,
headers: null
};
async componentDidMount() {
console.log("componentDidMOunt");
await axios
.get("https://api.iextrading.com/1.0/stock/aapl/financials?period=annual")
.then(res => {
const financials = res.data;
this.setState({ financials });
console.log(financials);
});
console.log("componentDidMount finished setting the data for the table");
}
render() {
// const headers = this.getHeaders1();
return (
<GridContainer>
<GridItem xs={12} sm={12} md={12}>
<Card>
{this.state.financials.financials.map(items => items)} <-- i want to get the data out of state and later put it into a table.
</Card>
</GridItem>
</GridContainer>
);
}
}
最佳答案
组件第一次渲染时,this.state.financials
为null
,因为您使用null
初始化它:
state = {
financials: null,
headers: null
};
这就是您收到该错误的原因。这是一个复制错误的简单示例:
var state = {
financials: null,
};
state.financials.financials.map(() => {});
您需要检查您的渲染方法是否设置了该值,如果没有设置什么也不做:
render() {
// const headers = this.getHeaders1();
if (!this.state.financials) {
return null; // or some message that the data is loading
}
return (
<GridContainer>
<GridItem xs={12} sm={12} md={12}>
<Card>
{this.state.financials.financials.map(items => items)} <-- i want to get the data out of state and later put it into a table.
</Card>
</GridItem>
</GridContainer>
);
}
或者,您可以使用 {financials: []}
来初始化它:
state = {
financials: {financials: []},
headers: null
};
然后您在 render
中的现有代码应该“工作”(见下文)。
但仅此一项可能无法使您的组件正常工作。您还需要将 this.state.financials.financials
中的条目实际转换为 React 可以呈现的内容。这是一个提取日期的示例:
this.state.financials.financials.map(item => item.reportDate)
根据您的需要进行调整。
关于javascript - 类型错误 : Cannot read property state of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531077/