我正在尝试设置一个刷新按钮,以便当最终用户创建新票证时,我应该能够在按下刷新按钮时看到新创建的票证。我正在利用 Apollo 客户端从 graphql 服务器获取数据。我想知道我应该如何刷新我尝试过的 table forceUpdate
和this.setState()
,我通过输入 {Math.random()}
来验证它是否有效。然而,在渲染函数中,它不会刷新并提供新数据,也尝试将刷新按钮放在button.js中,但问题仍然存在。 window.location.reload()
有效,但这不是我想要的,有没有什么 react 可以像任何生命周期 Hook 一样,我尝试过:
componentWillReceiveProps(nextProps) {
if(this.props.ticket !== nextProps.ticket) {
console.log(this.props.ticket)
}
}
在 table.js 中,但它没有起作用,或者我必须使用一些 Apollo 客户端 API。请建议,先谢谢了。
App.js
class App extends Component {
constructor(props) {
super(props);
this.handleRefresh = this.handleRefresh.bind(this);
}
handleRefresh() {
this.forceUpdate();
}
render() {
const { data: {loading, getTickets}} = this.props;
if(loading) {
return <h4>Loading..</h4>
}
const Data = getTickets.map((ticket, id) => {
return <Table ticket={ticket} key={id} />
})
return (
<div className="App">
<header className="App-header">
<Header />
<Button className="lookup" bsStyle="info" bsSize="xsmall"
onClick={this.handleRefresh}><h5>lookup 1</h5></Button><br/><br/>
<div className="container" style={{overflowX:"auto"}}>
<div className="table-responsive">
<table className="table table-bordered table-hover">
<thead>
<tr>
<th>TicketID</th>
<th>Name</th>
<th>Comment</th>
<th>EmpID</th>
</tr>
</thead>
<tbody>
{Data}
</tbody>
</table>
</div>
<h4>Random number : {Math.random()}</h4>
</div>
</header>
</div>
);
}
}
export default compose(
graphql(GetTickets)
)(App);
表.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Table extends Component {
constructor(props) {
super(props);
}
render() {
return (
<tr>
<td>{this.props.ticket.ticketID}</td>
<td>{this.props.ticket.name}</td>
<td>{this.props.ticket.comment}</td>
<td>{this.props.ticket.EmpID}</td>
</tr>
)
}
}
Table.propTypes = {
ticketID: PropTypes.number,
name: PropTypes.string,
EmpID: PropTypes.number,
comment: PropTypes.string
}
export default Table;
最佳答案
graphql 提供了一个 refetch
属性,用于在任何时候重新查询数据库。只需作为 Prop 传递给您的子组件,并在单击刷新按钮时调用该函数即可。请参阅文档:
https://www.apollographql.com/docs/react/essentials/queries.html#refetching
关于javascript - react : How to refresh the data in the table after button click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53822446/