【问题标题】:How to update component that is being rendered on route of 'react-router-dom'?如何更新正在“react-router-dom”路由上呈现的组件?
【发布时间】:2020-02-21 08:06:47
【问题描述】:

当我的应用程序运行 componentDidMount() 时,我会获取数据

async componentDidMount() {
  try {
    let players = await playersDAO.read();
    this.setState({ players: players });
  } catch (e) {
    console.log(e);
  }
}

然后将其显示在 Route 从 react-router-dom 渲染的组件上

<BrowserRouter>
  <Switch>
    <Route
      key="players"
      path="/players"
      render={() => <Players rows={this.state.players} />}
    />
  </Switch>
</BrowserRouter>

我不知道为什么,但是当获取数据时组件没有更新。也许(很有可能)我做错了什么,但谁能帮我解决一下?

题外话:我使用 Route 的渲染属性,因为我需要为我的组件传递 props,有人知道这样做的更好方法吗?

【问题讨论】:

  • 我认为您在滥用Router。如果您需要它来更新它对我来说意味着它不应该是 Route 而是组件树渲染。路由就像 html a 标签。
  • Routes are like html a tags 你好像在想&lt;Link&gt;s, @RafaelMora
  • @NicholasTower 不,我不是。我只是想向@CarlosJunior 解释使用Routes 是什么感觉。
  • @CarlosJunior:使用带有 path="/players" 的路由意味着玩家组件仅在 url 以“/players”结尾时才会呈现,如http://localhost:3000/players。那是你要的吗?如果是这样,您是否将网址设置为该网址(直接在您的地址栏中或通过单击适当的链接)?
  • @NicholasTower 正是...当用户输入http://localhost:3000/players 时,它会显示数据,但如果数据发生更改,组件不会更新

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

你可以使用history.push('/players')设置状态后调用路由。

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2018-06-04
    • 1970-01-01
    • 2020-05-06
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多