在Apollo客户端中,可以使用外部状态管理库来管理Apollo配置的外部状态。以下是一个使用Redux作为外部状态管理库的示例解决方法:
首先,安装所需的依赖:
npm install apollo-client react-apollo redux react-redux --save
接下来,创建一个Redux store,并将Apollo Client实例添加到Redux store中:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { ApolloProvider } from '@apollo/react-hooks';
import { ApolloLink } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { reducers } from './reducers';
const httpLink = createHttpLink({
uri: 'http://your-apollo-server-url/graphql',
});
const authLink = setContext((_, { headers }) => {
// 添加需要的请求头(如授权信息)到Apollo请求中
const token = localStorage.getItem('authToken');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
const apolloClient = new ApolloClient({
link: ApolloLink.from([authLink, httpLink]),
cache: new InMemoryCache(),
});
const store = createStore(
combineReducers({
apollo: apolloClient.reducer(),
// 添加其他的reducers
...reducers,
}),
applyMiddleware(apolloClient.middleware()),
);
export default store;
然后,在应用程序的入口文件中使用ApolloProvider
组件包装应用程序的根组件,并将Redux store传递给它:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ApolloProvider } from '@apollo/react-hooks';
import store from './store';
import App from './App';
ReactDOM.render(
,
document.getElementById('root')
);
现在,你可以在应用程序的组件中使用react-redux
库提供的connect
函数来连接Redux store,并使用react-apollo
库提供的useQuery
和useMutation
来执行Apollo查询和变更操作。
以下是一个使用Redux和Apollo Client的示例组件:
import React from 'react';
import { connect } from 'react-redux';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { gql } from '@apollo/client';
const GET_USER_QUERY = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
`;
const UPDATE_USER_MUTATION = gql`
mutation UpdateUser($id: ID!, $name: String!) {
updateUser(id: $id, name: $name) {
id
name
}
}
`;
const UserComponent = ({ userId }) => {
const { loading, error, data } = useQuery(GET_USER_QUERY, {
variables: { id: userId },
});
const [updateUser] = useMutation(UPDATE_USER_MUTATION);
if (loading) return Loading...
;
if (error) return Error :(
;
const handleUpdateUser = () => {
updateUser({
variables: {
id: userId,
name: 'New Name',
},
});
};
return (
{data.user.name}
);
};
const mapStateToProps = (state) => ({
userId: state.userId,
});
export default connect(mapStateToProps)(UserComponent);
在上述示例中,UserComponent
组件使用useQuery
和useMutation
来执行GraphQL查询和变更操作。userId
属性从Redux store中获取,并作为查询的变量传递给useQuery
。
通过这种方式,你可以使用Redux来管理Apollo客户端的外部状态,并将其与应用程序的其他状态和逻辑一起管理。