1

我有一个组件,它接收来自两个或三个 API 的新闻列表。组件第一次呈现时,会调用 api 并以componentDidMount 如下方式呈现数据:

componentDidMount() {
        this.state.platforms.forEach((platform, i) => {
            let objToSend = {
                phrase: this.props.searchParams.phrase,
                // this is the main place when input data changes
                ...this.props.searchParams.general_params,
                ...this.props.searchParams.platforms[i].api_params,
                stringPath: platform,
                apiPath: this.props.searchParams.platforms[i].apiPath,
            }
            this.props.loadData(objToSend)
            // this is the api call using redux which sends data as props to this component
 }

new 当短语更改时,我希望此组件重新渲染并重新运行 componentDidMount,但它不起作用,因为 componentDidMount 将运行一次。所以我使用了componentDidUpdate,但由于有很多调用,所以api正在不断更新。

每次更改短语时,如何使组件重新渲染并重新运行 componentDidMount

4

2 回答 2

3

您可以使用componentDidUpdate参数 ( previousProps, previousState) 检查是否发生了一些新更改。

例子

componentDidUpdate(previousProps, previousState) {
    if (previousProps.phrase !== this.props.phrase) {
        //Do whatever needs to happen!
    }
}

我以这种方式停止了我的情况的无限循环。

于 2019-08-24T07:06:03.297 回答
2

这是something()重新渲染时的一种方法。

import React, { Component } from 'react';
import { render } from 'react-dom';

const fakeFetch = (n) => {
  console.log(`Doing fake fetch: ${n}`)
  return n
}

class App extends Component {
  state = {
    value: false,
    number: 0,
  }

  componentDidMount() {
    const number = fakeFetch(this.state.number + 1);
    this.setState({ number })
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.value !== this.state.value) {
      const number = fakeFetch(this.state.number + 1);
      this.setState({ number })
    }
  }

  toggle = () => {
    this.setState(({ value }) => ({ value: !value }))
  }

  render() {
    return (
      <React.Fragment>
        <h1>Number: {this.state.number}</h1>
        <button onClick={this.toggle}>re-render</button>
      </React.Fragment>
    );
  }
}

render(<App />, document.getElementById('root'));

现场示例在这里

于 2019-01-06T13:29:35.357 回答