gpt4 book ai didi

javascript - 在React JS中收到来自Web套接字的通知后,如何重新呈现表组件?

转载 作者:行者123 更新时间:2023-12-03 11:55:07 25 4
gpt4 key购买 nike

我正在使用React表并加载一个页面,该页面显示带有从API提取的数据的表。我还监听Web套接字,现在,每当通过Web套接字发送内容时,Im都会打印控制台消息。现在,当我在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"
/>
);
}

最佳答案

您可以在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 });
};

关于javascript - 在React JS中收到来自Web套接字的通知后,如何重新呈现表组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46056865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com