我正在使用React表并加载一个页面,该页面显示一个包含从API获取的数据的表。我也正在收听网络套接字,现在,只要通过网络套接字发送内容,我就会打印一个控制台消息。现在,当我收到Web套接字上的任何更新时,我想重新加载表(进而进行API调用)。
class TableExp extends React.Component {
constructor() {
super();
this.state = {
tableData: [
{
resourceID: '',
resourceType: '',
tenantName: '',
dealerID: '',
status: '',
logFilePath: '',
supportPerson: '',
lastUpdatedTime: '',
},
],
//testMessage: [{ message: 'Initial Message' }],
};
}
componentDidMount() {
this.websocket = new WebSocket(socket);
this.websocket.onopen = () => {
axios.get('https://myapi.com', {
headers: {},
responseType: 'json',
})
.then((response) => {
this.setState({ tableData: response.data });
});
console.log('Socket Opened');
};
this.websocket.onmessage = (event) => {
const data = (JSON.parse(event.data));
const status = data.status;
console.log(data.status);
this.forceUpdate();
if (status === 'failed') {
console.log('Error message received');
this.reloadTable();
}
};
this.websocket.onclose = () => {
this.statusDispatcher('closed');
};
}
reloadTable() {
this.forceUpdate();
}
render() {
const { tableData } = this.state;
return (
<ReactTable
data={tableData}
noDataText="Loading.."
columns={[
{
columns: [
{
Header: 'Dealer ID',
accessor: 'dealerId',
id: "dealerId",
},
{
Header: 'Location',
id: "dealerId",
},
{
columns: [
{
filterable: false,
Header: 'File Path',
accessor: 'logFilePath',
},
{
filterable: false,
Header: 'Date',
accessor: 'Date',
},
],
},
]}
defaultPageSize={20}
style={{
height: '450px', // This will force the table body to overflow and scroll, since there is not enough room
}}
className="-striped -highlight"
/>
);
}
答案 0 :(得分:0)
您可以在setState
onmessage
this.websocket.onmessage = (event) => {
let data = [];
const status = data.status;
if (status === 'failed') {
console.log('Error message received');
// And do nothing, or empty table
} else {
data = JSON.parse(event.data);
}
this.setState({ tableData: data });
};