我正在将库material-table用于应用程序中的数据表。我正在设置数据道具以使用来自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);
答案 0 :(得分:2)
有一个解决方案,调用该功能来管理材料表的所有查询事件
您可以创建对表的React引用。在那一刻,您可以访问该功能。 如果需要,可以使用它直接将值传递给函数。
这些是步骤: 1-创建一个值并分配React.createRef() 让tableRef = React.createRef()
2-将其分配给名为tableRef
的材料表属性tableRef = {tableRef}
3-然后,当您需要更新表时,可以调用函数onQueryChange(),不带任何参数。
tableRef.current.onQueryChange()
例如:
`async apiDelete(IDs) {
try {
await Service.delete(IDs);
this.state.tableRef.current.onQueryChange();
} catch (e) {
console.log("Error Deleting" + e);
}
}`
您可以执行其他操作,例如:
this.state.tableRef.current.onQueryChange({filters: "value"});
请创建console.log(tableRef)以查看所有操作。
让我知道这是否对您有帮助 问候