在Relay Modern中考虑以下ReactJS组件:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { graphql } from "react-relay";
import { QueryRenderer } from "react-relay";
import environment from "../../relay/environment";
const CustomersQuery = graphql`
query CustomersQuery($versionId: ID!) {
viewer {
customers {
id
name
}
}
}
`;
class Customers extends Component {
handleRefresh = () => {
/// ???? ///
How to force relay to refetch data here ?
/// ???? ///
};
getCustomer = (customer) => {
return (
<div>
<p>Customer Data:</p>
<p>Id: {customer.id}</p>
<p>Name: {customer.name}</p>
</div>
);
}
handleContent = props => {
let customers = props.viewer.customers.map(customer => {
return this.getCustomer(customer);
});
return (
<div>
<button type="button" onClick={this.handleRefresh}>
Reload Screen
</button>
{customers}
</div>
);
};
render = () => {
return (
<QueryRenderer
environment={environment}
query={this.props.query}
render={({ error, props }) => {
if (error) {
throw new error;
} else if (props) {
return this.handleContent(props);
}
return <p>>Loading...</p>;
}}
/>
);
};
}
export default Customers;
强制组件重新加载handleRefresh
处理程序中的Relay数据的正确方法是什么?
答案 0 :(得分:0)
<QueryRenderer
environment={environment}
query={graphql`
query MyQuery
{
{
id
name
caption
url
}
`}
variables={{isUpdate: this.state.isUpdate}} //Change the state in case you want latest response, this variable will be ignored at the server
render={({error, props}) => {
if (error) {
console.error(error);
return <div>Error!</div>;
}
if (!props) {
return <div>Loading...</div>;
}
console.log("response from server --->" , JSON.stringify(props))
return <div></div>
}}
/>
您可以在api调用中添加add参数并将状态传递给该参数,更改状态以获取服务器的最新响应。
答案 1 :(得分:0)
我建议您将handleContent提取到新组件中,并从中继使用createRefetchContainer HOC。然后中继将注入一个可用于触发refetch的道具,例如:props.relay.refetch(...)
请参阅relay docs