我正在使用 ES6 创建一个 React-Rails 应用程序,并且我很难将数据从控制器传递到组件(以及返回)。
我的应用程序包含一个记录表单,它将新创建的记录推送到记录组件。
我的 Records 控制器中的代码是:
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
Records 组件的代码是:
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>
);
}
}
运行此代码时,我收到以下有关 Records 组件中的 render 方法的错误:
未捕获的类型错误:无法读取未定义的属性“地图”
我为这个问题的长度道歉,但我已经研究了一段时间,坦率地说我很困惑。
有谁知道为什么这不起作用?我非常感谢任何人可以提供的任何建议。谢谢!