【问题标题】:ComponentDidMount only fetching second data setComponentDidMount 只获取第二个数据集
【发布时间】:2021-03-22 10:34:12
【问题描述】:

我正在尝试为同一个反应组件获取两个不同的表,但是我似乎最终只获得了最新的输出。我相信这是因为我有 2 个单独的 ComponentDidMount 组件,但我不确定如何组合它们。我的代码目前如下所示:

constructor(props) {
    super(props);
    this.state = {items: [],locations: []}        
  } 
   
  componentDidMount() {
    fetch('/locationmenu')
    .then(response => response.json())
    .then(menu => this.setState({locations : menu}))}
  componentDidMount() {
    fetch('/clothesmenu')
    .then(response => response.json())
    .then(menu => this.setState({items : menu}))}

在这种情况下,似乎只添加了数据的 /clothesmenu 部分,如果我将两者切换,则只有 /locationmenu 存在。

谁能告诉我如何组合这些componentDidMounts,或者告诉我我在其他地方缺少什么?

【问题讨论】:

  • 这里只有一个定义。你正在用你的第二个版本跺你的第一个版本。

标签: javascript reactjs fetch state


【解决方案1】:

仅使用 1 个componentDidMount

componentDidMount() {
    fetch('/locationmenu')
    .then(response => response.json())
    .then(menu => this.setState({locations : menu}));

    fetch('/clothesmenu')
    .then(response => response.json())
    .then(menu => this.setState({items : menu}));
}

【讨论】:

  • 谢谢!太简单了,我不敢相信我没有尝试过! (虽然我遇到这个问题时是凌晨 1 点,所以疲倦可能没有帮助)
  • 不客气,你可以在同一个生命周期方法中做很多事情,这不是问题
【解决方案2】:

您可以简单地将它们组合成一个生命周期事件:

componentDidMount() {
    fetch('/locationmenu')
    .then(response => response.json())
    .then(menu => this.setState({locations : menu}))}
    
    fetch('/clothesmenu')
    .then(response => response.json())
    .then(menu => this.setState({items : menu}))}
}

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2016-10-18
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多