我正在寻找关于在POST成功后让表重新呈现的建议(表和表单在同一页面上)。我有通过API(Django-Rest-Framework)提供给表的数据,所以我不希望有一个回调来检查新数据的每一秒,因为这将不必要地锤击我的API。组件之间的关系是DataProvider,它是Table的父级。表单是它自己的组件。我认为我需要做的是在表单提交上有一个onClick事件,它将再次从API获取,并重新呈现表。我是React的新手,并且不知道如何实际执行此操作并且我没有在Google上找到很多成功(或者只查找具有1秒回调来更新时钟或其他内容的示例)。
以下是4个相互作用的文件:
App.js
your_script.sh > log.txt 2>&1
DataProvider.js
import React from "react";
import ReactDOM from "react-dom";
import DataProvider from "./DataProvider";
import Table from "./Table";
import Form from "./Form";
class App extends React.Component {
constructor(props) {
super(props);
};
}
render() {
return (
<React.Fragment>
<DataProvider endpoint="/api/properties/" method="GET" render={(data) => <Table data={data} />} />
<Form endpoint="/api/properties/" />
</React.Fragment>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
Table.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import cookie from 'react-cookies';
class DataProvider extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loaded: false,
placeholder: "Loading...",
};
}
static propTypes = {
endpoint: PropTypes.string.isRequired,
render: PropTypes.func.isRequired
};
componentDidMount() {
fetch(this.props.endpoint, {
credentials: 'include',
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': cookie.load('csrftoken')
},
})
.then(response => {
if (response.status !== 200) {
return this.setState({ placeholder: "Something went wrong" });
}
return response.json();
})
.then(data => this.setState({ data: data, loaded: true }));
}
render() {
const { data, loaded, placeholder } = this.state;
return loaded ? this.props.render(data) : <p>{placeholder}</p>;
}
}
export default DataProvider;
Form.js
import React from "react";
import PropTypes from "prop-types";
import shortid from "shortid";
const uuid = shortid.generate;
const Table = ({ data }) =>
!data.length ? null : (
<div className="column">
<h2 className="subtitle">
Your Properties <strong>({data.length})</strong>
</h2>
<table className="table is-striped">
<thead>
<tr>
{Object.entries(data[0]).map(el => <th key={uuid()}>{el[0]}</th>)}
</tr>
</thead>
<tbody>
{data.map(el => (
<tr key={el.id}>
{Object.entries(el).map(el => <td key={uuid()}>{el[1]}</td>)}
</tr>
))}
</tbody>
</table>
</div>
);
Table.propTypes = {
data: PropTypes.array.isRequired
};
export default Table;