我使用Rails 5.1和react-on-rails gem以及当前版本的react-table,并且遇到了如何从Rails获取数据到反应组件的问题。
WorkingHoursCs.jsx:
import ReactTable from 'react-table';
export default class WorkingHoursCs extends React.Component {
return (
<ReactTable
data={working_hours_cs_for_react}
columns={columns}
defaultPageSize={10}
className="-striped -highlight"
/>
)
}
}
Rails Controller WorkingHoursCsController,带有一个数组@working_hours_cs_for_react,我想加载到react组件中:
class WorkingHoursCsController < ApplicationController
def index
@search = WorkingHoursCs.ransack(params[:q])
@working_hours_cs = @search.result
@working_hours_cs_for_react = @search.result.to_json
end
并在app / views / working_hours_cs / index.html.erb中:
<%= react_component("WorkingHoursCs", working_hours_cs_for_react: @working_hours_cs_for_react, prerender: false) %>
但我在浏览器控制台中收到错误消息:
原始消息:未定义working_hours_cs_for_react
如何在react组件中提供@working_hours_cs_for_react?
答案 0 :(得分:1)
您的代码中需要进行一些重构,但要修复错误消息,请尝试:
<%= react_component("WorkingHoursCs", props: { working_hours_cs_for_react: @working_hours_cs_for_react }, prerender: false) %>
和
<ReactTable
data={this.props.working_hours_cs_for_react}
columns={columns}
defaultPageSize={10}
className="-striped -highlight"
/>