我正在使用React-Relay和Found。当用户注销时,应该正确刷新中继存储作为安全措施。
显然,建议的过程是实现可重置对象。
这是我的可重置中继(遵循found-relay#42的建议):
ResettableRelay.js
import {Environment, Network, RecordSource, Store} from "relay-runtime";
import {Resolver} from "found-relay";
function fetchQuery(operation, variables, cacheConfig, uploadables) {
return fetch("/graphql", {
method: "POST",
headers: headers,
body: JSON.stringify({
query: operation.text, // GraphQL text from input
variables,
}),
}).then(response => {
return(response.json());
});
}
class ResettableRelay {
environment = null;
resolver = null;
constructor() {
this.reset();
}
reset = function () {
const source = new RecordSource();
const environment = new Environment({
store: new Store(source),
network: Network.create(fetchQuery)
});
this.environment = environment;
this.resolver = new Resolver(environment);
console.log("Reset!");
}
}
const currentRelay = new ResettableRelay();
export default currentRelay;
这是我的index.js:
index.js
import currentRelay from "./ResettableRelay";
import Routes from "./Routes";
const Router = createFarceRouter({
historyProtocol: new BrowserProtocol(),
historyMiddlewares: [queryMiddleware],
routeConfig: Routes,
render: createRender({})
});
const mountNode = document.getElementById("root");
ReactDOM.render(
<Router
resolver={currentRelay.resolver}
/>, mountNode);
这是我的应用程序嵌套在Routes.js中:
onLogout = () {
clearLoginToken();
console.log(currentRelay.environment);
currentRelay.reset();
console.log(currentRelay.environment); //These two logged relay environments are different!
this.forceUpdate(); //Not sure if I need this
}
我仍然无法使用上述方法。注销时,即使环境属性已重置,解析程序道具也不会更新其环境。此外,{viewer}中继查询在登录或注销时不会更新。它仅在后续查询中更新。
答案 0 :(得分:0)
我发现this test component在found-relay
的回购中显示了可重新设置的路由器。
我在这里复制该测试的组件主题以供将来参考:
class ResettableRouter extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
resolver: this.createResolver(),
};
}
reset() {
this.setState({
resolver: this.createResolver(),
});
}
createResolver() {
return new InstrumentedResolver(createEnvironment(fetchSpy));
}
render() {
return <Router resolver={this.state.resolver} />;
}
}
我们的想法是将Router
包装到另一个组件中,以便使用新的解析器使用this.setState(...)
触发重新渲染。
如果您使用的是连接路线,我认为您应该能够将新环境/解析器作为道具传递。