现在我想我已经把它缩小到以下几点:
我有一个drivers
列表,其中包含cars
数组:
var driverSchema = new mongoose.Schema({
driver: String,
age: String,
cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }]
});
module.exports = mongoose.model('Driver', driverSchema);
可以像这样选择一个驱动对象ChoosenDriver:
this.setState({choosenDriver:driver})
问题是选中时对象会发生变化。它改变了:
drivers: array[3]
->0: {}
->1: {}
_v: 0
_id: "4242594395935934"
name: "Roger"
cars: Array[1]
到此:
choosenDriver: {..}
_v:0
_id: "235345353453"
name: "Roger"
cars:
->_proto_ :{..}
0: "4242594395935934",
_id: undefined
选择驱动程序后, cars
不再是数组。
有人遇到类似的东西吗?
更新: 我将驱动程序列表传递给子组件,如下所示:
<DriversList drivers={this.props.drivers}
在DriversList中我选择一个这样的驱动程序: (render-func应该足以告诉你)
handleDriverClick: function(i) {
this.props.setChoosenDriver(this.props.drivers[i])
},
render: function(){
var self = this;
var drivers = this.props.drivers.map(function(driver,i){
return <li key={driver._id} onClick={self.handleDriverClick.bind(null, i)}> {driver.name} </li>;
});
在父母:
setChoosenDriver: function(driver) {
this.props.setChoosenDriver(driver)
},
最后在GrandParent我设置状态:
setChoosenDriver: function(driver) {
this.setState({choosenDriver:driver})
},
更新
getInitialState: function() {
return {
drivers:[]
};
},
componentWillMount: function(){
var self = this;
request
.get(Driversurl)
.end(function(err, res){
self.setState({drivers: res.body});
});
},
它是一个带有以下对象的驱动程序数组:
{"_id":"5607b0747eb3eefc225aed61","name":"Moore","__v":0,"cars":["5607b0747eb3eefc225aed61","5607b07a7eb3eefc225aed62","5606bf4b0e76916c1d1668b4","5607b07a7eb3eefc225aed62"]}
答案 0 :(得分:0)
不要在componentWillMount中执行您的请求,这是非常错误的,请在componentDidMount中执行,有关详细信息,请参阅此内容:bind(this) not working on ajax success function
另外,当你收到结果时,我会解析你的请求结果,你的问题可能来自这里
self.setState({drivers:JSON.parse(res.body)});