【问题标题】:How do I render data from selected object?如何渲染选定对象的数据?
【发布时间】:2018-07-15 00:28:50
【问题描述】:

目前正在尝试学习使用 firebase 做出反应并不断遇到一些小障碍。

截至目前,我正在尝试在新页面中呈现所选项目的数据。索引页包含以下内容:

renderPosts(){
    return Object.keys(this.state.posts).map((post, index)=>(
        <div key={index} className="thumbnail">
        <h2>
          <Link to={`/view/posts/${post}`}>
            {this.state.posts[post].title}
          </Link>
        </h2>
        <p>{this.state.posts[post].body}</p>
        </div>
      ));
}

render() {
   return (
      <div>
        <div>
          {this.renderPosts()}
        </div>
        <View/>
      </div>
   )
}

如您所见,它将该帖子的 ID 附加到链接中,所以我现在要做的是返回到 firebase 并在新页面中单独呈现具有该 ID 的项目的相应数据。

ViewPost.js 文件如下:

constructor(props){
    super(props);
    this.state = {
      title: '',
      body: '',
    };
  }

  componentDidMount(){
    database.on('value', snapshot => {
      this.setState({
        post: snapshot.val()
      });
      this.props.match.params.postId;
    });
  }

  render() {
    return (
      <div >
       {this.state.props.title}
      </div>
    )
  }

你能告诉我我做错了什么以及怎么做吗?

【问题讨论】:

    标签: javascript reactjs firebase react-router


    【解决方案1】:

    您的示例中缺少一个部分,即您的路由器。首先,您需要向路由器添加一条新路由。

     <Route path='/view/posts/:postId' component={ViewPost}/>
    

    这是你在你创建的渲染方法中的链接标签中告诉路由器你想去的路由:

    <Link to={`/view/posts/${post}`}>
    

    我假设您在访问该链接时要呈现的组件是您在上面的 ViewPost.js 示例中编写的代码。如果您在路由器文件中将此组件作为ViewPost 导入,它现在应该可以工作了。

    单击链接,它将加载该组件。

    接下来,在组件内部,您要调用与您在 URL 中看到的键关联的数据。从您使用的 URL this.props.match.params.postId 中获取键值。

    现在您可以访问键值,您可以在 componentDidMount 中执行常规 firebase 调用:

    componentDidMount(){
        database
         .ref(`posts/${this.props.match.params.postId}`) 
         .on('value', snap => {
              this.setState({post: snapshot.val()});
         })
    }
    

    我希望这是有道理的。首先创建一个路由,然后从 URL 中获取 key 的值,然后使用 key 值在最终到达的组件内进行数据库请求。

    【讨论】:

    • 首先,网络请求需要一点时间,因此请在 viewPost 函数中将 {this.state.post.title } 替换为 {this.state.post &amp;&amp; this.state.post.title}。还将 post 的默认状态值设置为 null 或 undefined。只有当它有东西要显示时才会显示。
    • 在你的 fiddle 的 componentDidMount 方法中,datbase 和 ref 之间也有很大的空间。确保它不在您的实际代码中。
    • 什么是列表组件?您将其导入小提琴,然后从未使用过它。评论 。在我们调试时退出导入。
    • 我会保留视图功能,因为它只是杂乱无章。现在只需在 render 中渲染你需要的东西,而不是渲染函数。循环回到我们经历的调试过程。注释掉 view 中的 componentDidMount,然后控制台记录 this.props.match.params.postId 并查看控制台中是否显示任何内容。
    • 如果它现在对您有用,请接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多