class SubCategories extends React.Component<
SubCategoryStateProps
> {
constructor(props: RouteComponentProps<CategoryUrlParams>) {
super(props);
this.state = {
category: null,
};
}
componentDidMount() {
axios
.get(
window.location.origin + `/core/academix/categories/${this.CategoryId}`
)
.then((result: AxiosResponse<Category>) => {
if (result.status == 200) {
this.setState({
category: result.data,
});
}
})
.catch((error) => {
handleApiError(
error,
'Something went wrong when trying to load category details'
);
});
};
render() { <Title level={3}>{this.state.category.translations[1].name}</Title>);
}
}
export default SubCategories;
在初始状态下,我将category
设置为null,然后在SubCategoryStateProps中将其Categpry | null
设置为category
,将axios
设置为新状态但是在渲染之后,它仍然说类别是null
为什么?
答案 0 :(得分:1)
发生问题是因为axios.get
是一个异步调用,并且执行需要时间。同时,初始渲染被调用。由于this.state.category
仍为null
(因为axios.get
未完全执行),它将引发错误。
简单地认为这两个(axios.get
和render
)是并行运行的。
您要做的就是在渲染中进行null检查。