【发布时间】:2018-12-02 19:40:09
【问题描述】:
我正在为表格中的行项目创建一个反应元素。我为此使用 React-rails 并且遇到了一些奇怪的行为。
我的数据库中有一条记录,我的反应组件列出了重复的条目。这就是在 DOM 中呈现的内容。
<div class="table-responsive">
<div data-react-class="questions/QuestionLineItem" data-react-props="{"prompt":"What year was the NFL founded?","uuid":"f85c2f85-95d8-4037-963f-d1503b24123b"}" 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上查找有关参数的文档。也尝试更改为<%而不是<%=。
标签: javascript ruby-on-rails reactjs