将对象状态从null更改为设置状态的另一个

时间:2020-06-05 14:39:38

标签: reactjs typescript

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为什么?

1 个答案:

答案 0 :(得分:1)

发生问题是因为axios.get是一个异步调用,并且执行需要时间。同时,初始渲染被调用。由于this.state.category仍为null(因为axios.get未完全执行),它将引发错误。

简单地认为这两个(axios.getrender)是并行运行的。

您要做的就是在渲染中进行null检查。