我将 ReactJs 与 Material-UI 一起使用来显示汽车组件表,但在创建、编辑或删除行后从不更新。 接下来是结构:
class MainCar extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: []
};
this.apiUrl = "http://localhost:8080/api/v1/cars";
this.onCreate = this.onCreate.bind(this);
this.onUpdate = this.onUpdate.bind(this);
this.onDelete = this.onDelete.bind(this);
this.loadFromServer = this.loadFromServer.bind(this);
}
loadFromServer() {
fetch(this.apiUrl)
.then(response => response.json())
.then(json => {
this.setState({
cars: json.cars
});
});
}
onCreate(newCar) {
try {
const result =
fetch(this.apiUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newCar)
});
} catch(e) {
console.error(e);
}
this.loadFromServer();
}
onUpdate(car, updatedCar) {
try {
const result =
fetch(car._links.self.href, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedCar)
});
} catch(e) {
console.error(e);
}
this.loadFromServer();
}
onDelete(car) {
try {
const result =
fetch(car._links.self.href, {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(car)
});
} catch(e) {
console.error(e);
}
this.loadFromServer();
}
render() {
return (
<CarsTable cars={this.state.cars}
onCreate={this.onCreate}
onUpdate={this.onUpdate}
onDelete={this.onDelete} />
);
}
}
class CarsTable extends React.Component {
constructor(props) {
super(props);
}
render() {
const cars = this.props.cars.map(car =>
<Car key={car._links.self.href}
car={car}
onUpdate={this.props.onUpdate}
onDelete={this.props.onDelete} />
);
return (
<Table>
<TableBody>
{cars}
</TableBody>
</Table>
);
}
}
class Car extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<TableRow>
<TableCell>{car.code}</TableCell>
<TableCell>{car.color}</TableCell>
</TableRow>
);
}
}
如您所见,MainCar 在其状态上有汽车数组,但 CarTable 和 Car 只有属性。
当我登录渲染函数时,我看到数据已更改,但 View 未更新。
只查看更新
- 当我按 F5 更新页面时。
- 或者,当我创建、更新或删除新行时,我看到的是之前的更改,但看不到最后一次。
我读到 React 在状态改变时重新渲染一个组件。我应该为从 Prop 复制的 CarTable 和 Car 组件设置状态吗?我该如何解决这个问题?
提前致谢。
最佳答案
可能发生的情况是您的 GET 请求在您的 POST/PUT/DELETE 完成之前返回。解决此问题的一种方法是通过将 GET 放在 then
block 中来确保仅在其他操作完成后触发 GET。
例如
onDelete(car) {
try {
const result =
fetch(car._links.self.href, {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(car)
}).then(a => this.loadFromServer());
} catch(e) {
console.error(e);
}
}
关于javascript - 创建、编辑或删除新行后表不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62223208/