延迟componentDidMount获取以读取此prop.props

时间:2018-08-17 08:24:03

标签: javascript reactjs

我从data中以{p>的身份获取componentDidMount

this.setState({ isLoading: true });
fetch(
  `https://api.example.com/location/12345`
)
  .then(response => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error('Something went wrong ...');
    }
  })
  .then(data => this.setState({ data, isLoading: false }));

,这绝对可以。但是,如果我想将https://api.example.com/location/12345替换为https://api.example.com/location/${this.props.id}以允许id进行更改,则会收到错误提示,指出数据不存在。

这显然是因为fetch中的componentDidMount在读取this.props.id之前先获取了网址。

如何将fetch延迟到this.props.id可用?

2 个答案:

答案 0 :(得分:2)

一种方法是,只要组件收到新的ID,就使用componentDidUpdate生命周期方法获取数据,但要确保将prev ID值与新的ID值进行比较,并仅在它们不相同时进行调用。

赞:

componentDidUpdate(prevProps) {
    if(this.props.id && (prevProps.id != this.props.id)) {
        this._getData();
    }
}

_getData(){
    this.setState({ isLoading: true });
    fetch(
        `https://api.example.com/location/${this.props.id}`
    )
    .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Something went wrong ...');
        }
    })
    .then(data => this.setState({ data, isLoading: false }));
}

答案 1 :(得分:0)

我经常使用这种模式:

initFromProps(props: MyComponentProps) {
  const {  } = props;
}

componentWillMount() {
  this.initFromProps(this.props);
}

componentWillReceiveProps(nextProps: MyComponentProps) {
  this.initFromProps(nextProps);
}

这可确保您的组件在道具更改时以及启动时执行必要的操作。然后,在initFromProps中,您可以按照以下步骤进行操作:

initFromProps(props: MyComponentProps) {
  const { id } = props;

  if (id !== this.props.id) {
    this._getData(id);
  }

}