在同一个React应用程序中使用Redux、GraphQL和Apollo客户端可以通过以下步骤实现:
ApolloProvider
组件将Apollo客户端与React应用程序集成。connect
函数从Redux store中获取所需的状态和操作,并将其作为props传递给组件。graphql
函数将GraphQL查询与组件关联,并将查询结果作为props传递给组件。下面是一个示例代码:
// Step 1: 安装依赖
npm install redux react-redux graphql apollo-boost react-apollo
// Step 2: 创建Redux Store
// store.js
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
export default store;
// Step 3: 集成GraphQL和Apollo客户端
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from 'react-apollo';
import ApolloClient from 'apollo-boost';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
const client = new ApolloClient({
uri: 'https://example.com/graphql', // 替换为你的GraphQL endpoint
});
ReactDOM.render(
<ApolloProvider client={client}>
<Provider store={store}>
<App />
</Provider>
</ApolloProvider>,
document.getElementById('root')
);
// Step 4: 在组件中使用Redux和GraphQL
// App.js
import React from 'react';
import { connect } from 'react-redux';
import { graphql } from 'react-apollo';
import { getPosts } from './actions';
class App extends React.Component {
componentDidMount() {
this.props.getPosts(); // 使用Redux action获取帖子列表
}
render() {
const { loading, posts } = this.props;
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
{posts.map(post => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
}
}
const mapStateToProps = state => ({
posts: state.posts,
});
const mapDispatchToProps = dispatch => ({
getPosts: () => dispatch(getPosts()),
});
const AppWithRedux = connect(mapStateToProps, mapDispatchToProps)(App);
const GET_POSTS_QUERY = gql`
query {
posts {
id
title
}
}
`;
const AppWithReduxAndGraphQL = graphql(GET_POSTS_QUERY, {
props: ({ data }) => ({
loading: data.loading,
posts: data.posts,
}),
})(AppWithRedux);
export default AppWithReduxAndGraphQL;
这样,你就可以在同一个React应用程序中同时使用Redux、GraphQL和Apollo客户端了。请注意,以上示例代码仅为演示目的,实际应用中可能需要根据具体需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云