反应GraphQL Apollo和Redux。如何查询数据并将其放在商店的initialState中?

时间:2018-01-16 04:24:18

标签: reactjs redux graphql apollo-client graphcool

如何在Redux商店中从GraphQL / Apollo获取数据?这是我的输入文件。

...

render(
  (
    <ApolloProvider client={client}>
      <Provider store={store}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
      </Provider>
    </ApolloProvider>
  ),
  document.getElementById('root'),
);

这是商店

import { createStore, applyMiddleware, compose as composeRedux } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory';
import rootReducer from '../reducers';

export const history = createHistory();

const initialState = {};
const enhancers = [];
const middleware = [
  thunk,
  routerMiddleware(history),
];

if (process.env.NODE_ENV === 'development') {
  const { devToolsExtension } = window;

  if (typeof devToolsExtension === 'function') {
    enhancers.push(devToolsExtension());
  }
}

const composedEnhancers = composeRedux(
  applyMiddleware(...middleware),
  ...enhancers,
);

const store = createStore(
  rootReducer,
  initialState,
  composedEnhancers,
);

export default store;

我对我的App组件使用了以下查询

const LOGGED_IN_USER = gql`
  query LoggedInUser {
    loggedInUser {
      id
      facebookUserId
      facebookEmail
      facebookName
      facebookPicture
      facebookLocation
    }
  }
`;

export default compose(graphql(LOGGED_IN_USER, {
  options: {
    fetchPolicy: 'network-only',
  },
}))(App);

我应该将查询从App移动到商店吗?我输了。 ; - )

1 个答案:

答案 0 :(得分:0)

您需要将减速机与阿波罗减速机结合使用。您可以尝试以下方法: -

const client = new ApolloClient({
  networkInterface,
  dataIdFromObject: (o) => o.id
});

const middlewares = [thunk, logger];

const rootReducer = combineReducers({
  wlStore: wlReducer,
  apollo: client.reducer()
});

const store = applyMiddleware(...middlewares, client.middleware())(createStore)(rootReducer);

你的商店会是这样的: -

store: {
  wlStore: {
    // redux store
  },
  apollo: {
    // apollo store
  }
}