我正在为我的应用程序中的数据表使用库材料表。我将数据道具设置为使用来自 this.state.data 的数据,并且添加行将使用 setState 在我的表上更新。但是在切换到远程数据后,表格在添加一行后不会更新。有没有另一种方法可以通过远程数据实现这一目标?
import React, {Component} from "react";
import MaterialTable from "material-table";
import Add from "@material-ui/icons/Add";
import Clear from "@material-ui/icons/Clear";
import Check from "@material-ui/icons/Check";
import Edit from "@material-ui/icons/Edit";
import FirstPage from "@material-ui/icons/FirstPage";
import ChevronRight from "@material-ui/icons/ChevronRight";
import LastPage from "@material-ui/icons/LastPage";
import ChevronLeft from "@material-ui/icons/ChevronLeft";
import Search from "@material-ui/icons/Search";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component {
state = {
data: []
}
render() {
return (
<MaterialTable
columns={[
{
title: "Avatar",
field: "avatar",
render: rowData => (
<img
style={{ height: 36, borderRadius: "50%" }}
src={rowData.avatar}
/>
)
},
{ title: "Id", field: "id" },
{ title: "First Name", field: "first_name" },
{ title: "Last Name", field: "last_name" }
]}
icons={{
Add: () => <Add />,
Check: () => <Check />,
Clear: () => <Clear />,
Edit: () => <Edit />,
FirstPage: () => <FirstPage />,
NextPage: () => <ChevronRight />,
LastPage: () => <LastPage />,
PreviousPage: () => <ChevronLeft />,
ResetSearch: () => <Clear />,
Search: () => <Search />
}}
// If this is an array from state(ie. this.state.data) then it works.
data={query =>
new Promise((resolve, reject) => {
let url = "https://reqres.in/api/users?";
url += "per_page=" + query.pageSize;
url += "&page=" + (query.page + 1);
fetch(url)
.then(response => response.json())
.then(result => {
resolve({
data: result.data,
page: result.page - 1,
totalCount: result.total
});
});
})
}
editable={{
onRowAdd: newData =>
new Promise((resolve, reject) => {
setTimeout(() => {
{
const data = this.state.data;
data.push(newData);
this.setState({ data }, () => resolve());
}
resolve();
}, 1000);
})
}}
title="Remote Data Example"
/>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);