【问题标题】:Duplicate table rows rendered in React-rails在 React-rails 中呈现的重复表行
【发布时间】:2018-12-02 19:40:09
【问题描述】:

我正在为表格中的行项目创建一个反应元素。我为此使用 React-rails 并且遇到了一些奇怪的行为。

我的数据库中有一条记录,我的反应组件列出了重复的条目。这就是在 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>

一条记录被正确呈现到表格中,但另一条记录漂浮在顶部,没有嵌套在表格中。我的 item 组件很简单。

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

【问题讨论】:

  • 你如何分配@questions?我们可以看看你的控制器代码吗?
  • 您的 html 视图对我来说看起来很正常(与控制器和反应代码相同),您提到的重复项在哪里?也许是屏幕截图?
  • @kasperite QuestionLineItem 被渲染两次,第一次在div.table-responsive 中,第二次在tbody 中正确地渲染
  • 我不了解 react-rails,但我会在 react_component,尤其是 prerender 上查找有关参数的文档。也尝试更改为&lt;% 而不是&lt;%=

标签: javascript ruby-on-rails reactjs


【解决方案1】:

您是否尝试将&lt;React.Fragment&gt; 添加到您的 React 组件的输出中? 它看起来像这样:

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

作为参考,你可以在这里阅读更多关于 React.Fragments here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多