React GraphQL Apollo 和 Redux。如何查询数据并将其置于 store 的 initialState 中?
Posted
技术标签:
【中文标题】React GraphQL Apollo 和 Redux。如何查询数据并将其置于 store 的 initialState 中?【英文标题】:React GraphQL Apollo and Redux. How to query data and place it in initialState of the store? 【发布时间】:2018-06-24 17:43:31 【问题描述】:如何在我的 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 移动到商店吗?我迷路了。 ;-)
【问题讨论】:
您需要 Redux 存储中的数据吗?只是问一下,因为也许你想用 Redux 和 Apollo Client 分离视图状态和数据状态。 【参考方案1】:你需要把你的减速器和阿波罗的减速器结合起来。您可以尝试以下方法:-
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
【讨论】:
以上是关于React GraphQL Apollo 和 Redux。如何查询数据并将其置于 store 的 initialState 中?的主要内容,如果未能解决你的问题,请参考以下文章
GraphQL“必须提供查询字符串” graphql-tag react-apollo
如何使用 React-Apollo 处理 GraphQL 错误?
graphql_devise 用于 Rails/Graphql/Apollo/React 中的身份验证。 “字段需要身份验证”错误