首页 > 解决方案 > React Router:从 Api 为 Json 数据创建单个页面

问题描述

我有一个应用程序,它从 api 呈现用户列表,我想要做的是当用户单击列表之一时,它通过 React Router 指向该用户信息页面。在 React 上实现这一点的最佳方法是什么?

我试图解决它,但没有一个好结果。

代码很敏感,但这是我到目前为止所做的图片:索引组件:

我可以访问页面但无法传递要呈现的数据

标签: reactjsreact-router-v4

解决方案


使用Linkfromreact-router-dom通知您的路由器位置已更改,然后让路由器对其进行评估并确定它是它加载的视图/容器。

这是一个工作示例: https ://reacttraining.com/react-router/web/example/basic


以下是一些关于如何使用路由器获取这些详细信息的示例代码:

--- Router 的使用示例并传入它的 props:

 <Route
    exact
    path="/user/view/:id"
    render={props => <CustomerView user={this.state.user} {...props} />
    }
  />

 // By spreading the props into the View you have access to the this.props.match.params.id

--- 在您的用户容器中

  fetchUser = () => {
    const id = this.props.match.params.id;
    postData("/documents/fetch-document", { id: id }).then(res => {
      this.setState({
        document: res,
        ...this.defaultState,
        isLoading: false
      });
    });
  };

推荐阅读