Updating React state with Relay

2019-05-29 23:58发布

问题:

With Relay, you create a React component as usual:

class TodoApp extends React.Component {
  ...
}

And then component is wrapped in a Relay container:

export default Relay.createContainer(TodoApp, {
  ...
});

The Relay container will fetch data using GraphQL and then update the state. This is a higher order component and this state is then passed down as props to its children.

This isn't (or doesn't appear to be) compatible with a flux implementation like Redux. Redux has a single global state object and it too has higher order components that pass props down to presentational components. So I don't see how both the Redux store and Relay containers can coexist currently.

So then how should we update state that doesn't come from the database? How is this state supposed to be managed with Relay?

回答1:

While I can’t offer you an advice on using them together, technically you can definitely have several higher order components applied one after another:

class TodoApp extends React.Component {
  // ...
}

TodoApp = connect(
  // ...
)(TodoApp);

TodoApp = Relay.createContainer(TodoApp, {
  // ...
});

export default TodoApp;

I’m not sure this makes a lot of sense, but it’s easily doable.



回答2:

These things are still in discussion and the current state of Redux and Relay may not fit well together if you use a Relay container.

You can join the discussion here



回答3:

I've done this as follows for a chat application:

  1. The chat component (ChatComponent) is a dumb react component that expects all data to come as props. It also requires the redux dispatch function as a prop so it can dispatch actions when someone wants to send a new message. This is a 'private' component and is wrapped by...
  2. ChatComponentRelay - this renders ChatComponent but is a Relay component which is also connected to the redux store. It uses one of the lifecycle methods (not the constructor) to dispatch the data received via relay into the redux store. This is the component that is used by the rest of the application, and is basically just a proxy to the underlying dumb ChatComponent. It renders ChatComponent passing in all the data in its props from the redux store, and also the redux dispatch function as well.