首页 > 解决方案 > 从侧边栏菜单更新反应组件

问题描述

我有一个简单的反应应用程序,它由 3 个组件组成: 1. 包含链接的 SideBar 2. 包含表中数据的 ItemList 3. 包装它们的包装器(我从这里的一些帖子中了解到它有时很有用,因为我想要在单击侧边栏上的不同链接后更新 ItemsList 组件)。

我现在的工作:

在主包装器组件中:

  render() {
    return (
        <div>
            <SideMenu handleClick={this.handleClick} />
            <ItemsList url={this.state.currentUrl} />
        </div>
    );

}

应用程序启动后,立即使用 ItemsList 组件中的 componentDidMount() 获取数据并显示它。效果很好。

问题是,当我单击 sideMenu 组件中的链接时,我正在更改主包装器状态下的 currentUrl,因此它将被新的 url 重新呈现:

  handleClick() {
    this.setState({ currentUrl: 'here I put the new address to fetch from'});
}

但获取的是位于前一个 url 中的数据,而不是我刚刚将其更改为的数据。基本上,在我调试并检查更改后的状态之后,currentUrl 保持之前的状态,然后它使用之前的 url 重新呈现 ItemList。

我的问题是,如何使用这个 handleClick() 方法更改 itemList 的内容?希望我能得到一些见解。非常感谢您,非常感谢您的帮助。

主包装代码:

class MainWrapper extends React.Component {
constructor() {
    super();
    this.state = {
        currentUrl: 'current url to fetch from...',
        data: []
    };
    this.handleClick = this.handleClick.bind(this);
}

handleClick() {
    this.setState({ currentUrl: 'the new url ' });
}


render() {
    return (
        <div>
            <SideMenu handleClick={this.handleClick} />
            <ItemsList url={this.state.currentUrl} />
        </div>
    );

}

}

我的项目列表组件:

class ItemsList extends Component {

  constructor(props) {
    super(props);
    this.state = { url: props.url, data: [] };
  }

  componentDidMount() {
    return fetch(this.state.url)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({ data: responseJson.data });
      })
  }

  render() {
    return (
      displaying the table html tags..

        }
      </div>
    )
  }
}

标签: reactjssetstate

解决方案


您可以componentDidUpdate在 itemList 组件中使用生命周期方法。每次 url 更改时,listItem 可能会根据我从您的问题中理解的内容重新呈现,因此该componentDidUpdate方法将触发。正是在这种方法中,您可以检查新的 url 并发出新的请求。

在这里查看更多。


推荐阅读