Javascript ReactJs,DOM不会得到更新
在以下代码中:Javascript ReactJs,DOM不会得到更新,javascript,reactjs,Javascript,Reactjs,在以下代码中: componentDidUpdate(){ let self = this; this.state.carsOfChoosenDriver = []; // array where I want to save the cars belonging to the choosenDriver if (typeof this.state.choosenDriver.cars !== 'undefined'){ this.state.choose
componentDidUpdate(){
let self = this;
this.state.carsOfChoosenDriver = []; // array where I want to save the cars belonging to the choosenDriver
if (typeof this.state.choosenDriver.cars !== 'undefined'){
this.state.choosenDriver.cars.forEach(function(entry) {
request
.get('api/cars/' + entry)
.end(function(err, res){
self.state.carsOfChoosenDriver.push(res.body);
console.log(self.state.carsOfChoosenEvent);
});
});
}
}
handleEventClick(i){
this.setState({choosenDriver: this.state.drivers[i]});
}
我从触发handleEventClick的列表中选择一个驱动程序。
choosenDriver.cars包含一个id数组,我使用该数组从db获取car对象。这一切都起作用,res被记录在控制台中
但是dom不会在第一次单击handleEventClick时得到更新
在render方法中,我有以下内容:
render() {
let cars = this.state.carsOfChoosenDriver.map(function(car, i){
return <li key={i}>{car.name}</li>;
});
return (
<div className="col-md-8">
{cars}
</div>
);
}
您应该将componentDidUpdate中的代码移到componentWillUpdate 在渲染完成刷新所有DOM更新后调用componentDidUpdate,这不是您想要的,因为您希望反映由handleEventClicki引起的状态更改 在渲染之前调用componentWillUpdate,这将在触发渲染之前完成self.state.CarsOfChooseEndRiver更改 此外,您应该使用setState,而不是手动修改组件状态,这不会触发渲染 尝试使用设置状态
因为React中的setState是异步的,但它会触发render,render将在刷新DOM之前等待异步完成 是否可以检查在第一次handleEventClick时是否调用了render?如果不是,则可能是shouldComponentUpdate生命周期方法存在问题是的,通过在render方法中添加警报,我可以看到它在componentDidUpdatethank中进行日志记录之前被调用,但它不起作用。当使用componentWillUpdate时,即使控制台在第一次单击时也不会记录任何内容,您的componentDidMount或componentWillMount是什么样子的?我在问题中添加了一个更新。I component didmount I调用数据库并获取所有驱动程序。我觉得您不应该手动修改self.state.carsOfChoosenDriver,而应该使用setState。对于self.state.carsOfChoosenDriver.pushres.body;console.logself.state.carsofChooseEvent;尝试使用setState。因为React中的setState是异步的,但render将在刷新DOM之前等待异步完成。谢谢,在componentDidUpdate中调用setState的问题在于setState调用componentDidUpdate,从而创建一个无限循环。
componentDidMount() {
let self = this;
request
.get('api/driver')
.end(function(err, res){
self.setState({drivers: res.body});
});
}
.end(function(err, res){
self.state.carsOfChoosenDriver.push(res.body);
console.log(self.state.carsOfChoosenEvent);
});
.end(function(err, res){
self.setState({carsOfChoosenDriver: res.body});
console.log(self.state.carsOfChoosenEvent);
});