【问题标题】:Re-render App component after child component API get request?子组件API获取请求后重新渲染App组件?
【发布时间】:2019-04-18 18:55:53
【问题描述】:

这里有点混乱。我有一个 App 组件,它执行获取 API 请求以使用属性卡填充页面。我的属性组件呈现一个侧边栏来过滤这些卡片。该侧边栏中的链接进行了正确的 API 调用,并获得了正确的响应——但该响应不会导致 App 组件使用更少的属性重新渲染。

我认为我需要在 App 中使用 ComponentDidUpdate 方法,或者在 Properties 中扩展 ComponentDidUpdate 方法,但我不确定是哪个。有人能指出我正确的方向吗?

应用组件

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      properties: [],
    };
  }

  componentDidMount() {
    Axios.get('http://localhost:3000/api/v1/PropertyListing')
      .then((response) => {
        this.setState({
          properties: response.data,
        });
      });
  }

  render() {
    return (
      <div className="navigation">
        <NavBar />
        <Switch>
          <Route exact path="/" component={Properties} />
          <Route exact path="/add-property" component={AddProperty} />
        </Switch>
        <PropertyCards
          properties={this.state.properties}
        />
      </div>
    );
  }
}

属性组件

class Properties extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      properties: [],
    };
  }

  componentDidUpdate(prevProps) {
    const { search } = this.props.location;

    if (prevProps.location.search !== search) {
      Axios.get(`http://localhost:3000/api/v1/PropertyListing${search}`)
        .then(({ data: properties }) => this.setState({ properties }))
        .catch(err => console.error(err));
    }
  }

  render() {
    return (
      <div className="sidebar">
        <h4>Filter by city</h4>
        <div className="filters">
          <Link className="filter" to={'/?query={"city":"Manchester"}'}>Manchester</Link>
          <Link className="filter" to={'/?query={"city":"Leeds"}'}>Leeds</Link>
          <Link className="filter" to={'/?query={"city":"Sheffield"}'}>Sheffield</Link>
          <Link className="filter" to={'/?query={"city":"Liverpool"}'}>Liverpool</Link>
        </div>
      </div>
    );
  }
}

【问题讨论】:

    标签: reactjs components rendering


    【解决方案1】:

    一般来说,将第二个 api 请求上移到你的父组件中是个好主意,这样你的“属性”组件就变成了一个“哑”组件,它只根据传递的数据呈现 ui。这样您就不必维护多个状态。

    在这种情况下,将 ComponentDidUpdate() 也移动到您的“App”组件肯定是有意义的。

    【讨论】:

    • 感谢您回复此问题,Fabian - 非常感谢。我同意你的观点,但是当我将 ComponentDidUpdate 从 Properties 移动到 App 时,我收到一条错误消息,提示“搜索未定义”。
    • 您需要将一个方法传递给您的路由,以允许它们更新您的 App 组件的状态&lt;Route path='/' component={Properties} setLocation={this.setLocation} /&gt;
    • 仍然得到完全相同的错误,即使通过了那个方法!
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 2018-05-01
    • 2020-01-12
    • 2019-02-22
    • 2018-08-12
    • 2019-06-01
    • 2020-02-13
    • 2021-11-06
    相关资源
    最近更新 更多