代码之家  ›  专栏  ›  技术社区  ›  Trenton Tyler

在React rails中呈现的重复表行

  •  0
  • Trenton Tyler  · 技术社区  · 6 年前

    我正在为表中的行项目创建react元素。我正在使用React rails来处理这个问题,并且遇到了一些奇怪的行为。

    我的数据库中有一条记录,我的react组件列出了重复的条目。这就是DOM中呈现的内容。

    <div class="table-responsive">
        <div data-react-class="questions/QuestionLineItem" data-react-props="{&quot;prompt&quot;:&quot;What year was the NFL founded?&quot;,&quot;uuid&quot;:&quot;f85c2f85-95d8-4037-963f-d1503b24123b&quot;}" data-hydrate="t">
    <tr><td>f85c2f85-95d8-4037-963f-d1503b24123b</td><td>What year was the NFL founded?</td></tr>
        </div>
        <table class="table table-striped table-sm">
            <thead>
            <tr>
                <th>UUID</th>
                <th>Question</th>
            </tr>
            </thead>
            <tbody>
                <tr data-reactroot=""><td>f85c2f85-95d8-4037-963f-d1503b24123b</td><td>What year was the NFL founded?</td></tr>
            </tbody>
        </table>
    </div>
    

    一条记录被正确地呈现到表中,但另一条记录浮动在顶部,而不是嵌套在表中。我的项目组件非常简单。

    import React from "react";
    import PropTypes from "prop-types";
    class QuestionLineItem extends React.Component {
      render() {
        return (
          <tr>
            <td>{this.props.uuid}</td>
            <td>{this.props.prompt}</td>
          </tr>
        );
      }
    }
    
    QuestionLineItem.propTypes = {
      prompt: PropTypes.string
    };
    
    export default QuestionLineItem;
    

    该视图只是一个简单的表,在活动记录集合中的所有项上循环。

    <div class="table-responsive">
        <table class="table table-striped table-sm">
            <thead>
            <tr>
                <th>UUID</th>
                <th>Question</th>
            </tr>
            </thead>
            <tbody>
            <% @questions.each do |q| %>
                <%= react_component('questions/QuestionLineItem', { prompt: q.prompt, uuid: q.uuid }, { prerender: true} ) %>
            <% end %>
            </tbody>
        </table>
    </div>
    

    有人能解释这种行为吗?

    问题控制器仅包含索引操作。

    class QuestionsController < ApplicationsController 
        def index
            @questions = Question.all
        end
    end
    

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  0
  •   Laszlo-JFLMTCO    6 年前

    你试过添加 <React.Fragment> 你的反应组件的输出? 它看起来是这样的:

    class QuestionLineItem extends React.Component {
      render() {
        return (
          <React.Fragment>
            <tr>
              <td>{this.props.uuid}</td>
              <td>{this.props.prompt}</td>
            </tr>
          </React.Fragment>
        );
      }
    }
    

    作为参考,这里你可以阅读反应。碎片更多 here