我正在创建一个使用ES6的React-Rails应用程序,而且我无法将数据从控制器传递到组件(并返回)。在React-Rails应用程序中,将实例变量从控制器传递到组件(并返回)
我的应用程序包括一个记录表单,将新创建的记录推送到记录组件。
我的记录器中的代码是:
class RecordsController < ApplicationController
def index
@records = Record.all
end
def create
@record = Record.new(record_params)
if @record.save
render json: @record
else
render json: @record.errors, status: :unprocessable_entity
end
end
private
def record_params
params.require(:record).permit(:title, :date, :amount)
end
end
的记录部件的代码是:
class Records extends React.Component {
constructor (props) {
super(props);
}
componentWillMount() {
var records = this.records;
this.state = {records: records};
}
addRecord (record) {
var records;
records = this.state.records;
records.push(record);
this.setState({records: records});
}
render() {
var records = this.records.map(function(record) {
return <Record key={record.id} data={record} />;
});
return (
<div>
<h2>Records</h2>
<RecordForm handleNewRecord={this.addRecord()} />
<table>
<thead>
<tr>
<th>Title</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{records}
</tbody>
</table>
</div>
);
}
}
的记录表单组件的代码是:
class RecordForm extends React.Component {
constructor (props) {
super (props);
this.state = {
title: "",
date: "",
amount: ""
}
this.handleNewRecord = this.props.handleNewRecord.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange (e) {
var stateObject = function() {
returnObj = {};
returnObj[this.target.name] = this.target.value;
return returnObj;
}.bind(e)();
this.setState(stateObject);
}
handleSubmit (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: {record: this.state},
success: function (data) {
this.props.handleNewRecord();
this.setState({title: "", date: "", amount: ""})
},
dataType: 'JSON'
});
}
render() {
return (
<form className="form-inline" onSubmit={this.handleSubmit} >
<div className="form-group">
<input
type="text"
className="form-control text"
placeholder="Date"
name="date"
value={this.state.date}
onChange={this.handleChange}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="Title"
name="title"
value={this.state.title}
onChange={this.handleChange}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="Amount"
name="amount"
value={this.state.amount}
onChange={this.handleChange}
/>
</div>
<input
type="submit"
value="Create Record"
className="btn btn-primary"
/>
</form>
);
}
}
的Record组件的代码是:
class Record extends React.Component {
render() {
return (
<tr>
<td><em>{this.props.data.title}</em></td>
<td>{this.props.data.date}</td>
<td>{this.props.data.amount}</td>
</tr>
);
}
}
当我运行这段代码,我收到关于渲染方法在记录部件以下错误:
Uncaught TypeError: Cannot read property 'map' of undefined
我对这个问题的长度道歉,但我一直在努力了而我坦白地说,他已经失败了。
有没有人有一个想法,为什么这不工作?我完全赞赏任何人都可以提供的建议。谢谢!
您可以添加视图代码吗?例如,你使用'react_component' helper吗? – rmosolgo