大佬教程收集整理的这篇文章主要介绍了node.js – 如何避免客户端使用redux在react-apollo SSR中重新获取?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
服务器.js
import express from 'express'; import bodyParser from 'body-parser'; import path from 'path'; import expressGraphQL from 'express-graphql'; import scheR_806_11845@a from './GraphQL/scheR_806_11845@a'; import React from 'react'; import ReactDOMServer from 'react-dom/server' import { StaticRouter } from 'react-router'; import { ApolloClient,createNetworkInterface,ApolloProvider } from 'react-apollo'; import { getDataFromTree } from "react-apollo" import store from '../client/Redux/Store/store'; import {serverClient} from './lib/apollo' require('es6-promise').polyfill(); require('isomorphic-fetch'); import WApp from '../client/App'; //Dev HMR import HMR from './serverUtils/HMR'; const app = express(); app.use(bodyParser.json()); app.use('/api',expressGraphQL({ scheR_806_11845@a,graphiql: true })); app.use('/static',express.static('build')); HMR(app); function Html({ content,state }) { return ( <html> <body> <div id="app" dangerouslySeTinnerHTML={{ __html: content }}/> <script src="/static/app.js" /> <script dangerouslySeTinnerHTML={{ __html: `window.__APOLLO_STATE__=${JSON.Stringify(statE).replace(/</g,'\<')};`,}} /> </body> </html> ); } function createReactHandler(req) { return async function reactHandler(ctX) { const routeContext = {}; const client = serverClient(); const components = ( <StaticRouter LOCATIOn={req.url} context={routeContext}> <ApolloProvider store={storE} client={Client}> <WApp /> </ApolloProvider> </StaticRouter> ); await getDataFromTree(components); // const html = ReactDOMServer.renderToString(components); // // Handle redirects // if ([301,302].includes(routeContext.status)) { // // 301 = peRMANent redirect,302 = temporary // ctx.status = routeContext.status; // // // Issue the new `LOCATIOn:` header // ctx.redirect(routeContext.url); // // // Return early -- no need to set a response body // return; // } // // // Handle 404 Not Found // if (routeContext.status === 404) { // // By default,just set the status code to 404. You can add your // // own custom logic here,if you want to redirect to a peRMANent // // 404 route or set a different response on `ctx.body` // ctx.status = routeContext.status; // } // return html; // console.log(html) } } const HTML = ({ html,statE}) => ( <html lang="en" prefix="og: http://ogp.me/ns#"> <head> <Meta charSet="utf-8" /> <Meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <Meta httpEquiv="Content-Language" content="en" /> <Meta name="viewport" content="width=device-width,initial-scale=1" /> </head> <body> <div id="app" dangerouslySeTinnerHTML={{ __html: html }} /> <script dangerouslySeTinnerHTML={{ __html: `window.__STATE__=${JSON.Stringify(statE)};`,}} /> <script src="/static/app.js" /> </body> </html> ); app.get('/*',(req,res) => { const routeContext = {}; const client = serverClient(); const components = ( <StaticRouter LOCATIOn={req.url} context={routeContext}> <ApolloProvider store={storE} client={Client}> <WApp /> </ApolloProvider> </StaticRouter> ); getDataFromTree(components).then(() => { const html = ReactDOMServer.renderToString(components); const initialState = {apollo: client.geTinitialState()} console.log(client); res.send(`<!DOCTYPE html>\n${ReactDOMServer.renderToStaticMarkup( <HTML html={html} state={initialStatE} />,)}`) }) }) app.listen(3000,() => { console.log('Man I on') })
store.js
import { createStore,compose,applymiddleware } from 'redux'; import { syncHistoryWithStore } from 'react-router-redux'; import thunk from 'redux-thunk'; import {CreateLogger} from 'redux-logger'; import client from '../apolloClient'; import rootReducer from '../Reducers' //All Reducer import {initialState as allPosts} from '../Reducers/AllPosts_Reucer'; const isProduction = process.env.NODE_ENV !== 'development'; const isClient = typeof document !== 'undefined'; const initialState = { allPosts }; const middlewares = [thunk,client.middleware()]; const enhancers = []; if (!isProduction && isClient) { const loggerMiddleware = createLogger(); middlewares.push(loggerMiddlewarE); if (typeof devToolsExtension === 'function') { const devToolsExtension = window.devToolsExtension; enhancers.push(devToolsExtension()); } } const composedEnhancers = compose( applymiddleware(...middlewares),...enhancers ); const store = createStore( rootReducer,{},composedEnhancers,); export default store;
apolloClient.js
import ApolloClient,{ createNetworkInterface,} from 'apollo-client'; const isProduction = process.env.NODE_ENV !== 'development'; const testurl = 'http://localhost:3000/api'; // const url = isProduction ? productionUrl : testurl; const url = testurl; const client = new ApolloClient({ networkInterface: createNetworkInterface({uri:testurl}),dataIdFromObject:({iD}) => id,initialState: (typeof window !=='undefined')? window.__STATE__:{},reduxRootSELEctor:state => state.custom }); export default client;
Home.js
import React,{Component} from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; import * as postActions from '../../Redux/Actions/postActions'; class Home extends Component{ componentWillMount(){ // console.log('From Will Mount',this.props.posts) } renderAllPost(){ const {loading,posts} = this.props; if(!loading){ return posts.map(data => { return <li key={data.iD}>{data.@R_772_10283@E}</li> }) }else{ return <div>loading</div> } } render(){ return( <div> {this.renderAllPost()} </div> ) } } //start from here const GetallPosts = gql` query getAllPosts{ posts{ id @R_772_10283@e body } } `; const mapDispatchToProps = (dispatch) => ({ actions:bindActionCreators( postActions,dispatch ) }); const containerWithData = graphql(GetallPosts,{ props:({ data:{loading,posts} }) => ({ posts,loading,}) })(HomE) export default connect( // mapStateToPros,// mapDispatchToProps )(ContainerWithData)
您正在呈现HTML服务器端.
> HTML(包括所有帖子)都在HTML中返回给浏览器.
> React然后将其更改为加载窗口
> React然后进行API调用,并呈现新帖子
注意:Apollo将始终进行AJAX调用,因为这是作为ContainerWithData的一部分自动完成的.
解
使用所有数据渲染Redux Store.
例如,在调用“createStore”时,您当前正在传入一个空对象.如果您在此处进行AJAX调用,则可以使用所需的所有数据填充browser / redux存储.
此时,您可以在Container中删除对GraphQL的调用.您可以使用“componentWillMount”将其替换为某些逻辑.
逻辑是:
>使用API返回的模型数据创建商店
>呼叫家庭组件
>本垒打“componentWillMount”
> componentWillMount检查store.posts是否包含数据
>然后从API加载数据(GraphQL)> else返回true并继续渲染
以上是大佬教程为你收集整理的node.js – 如何避免客户端使用redux在react-apollo SSR中重新获取?全部内容,希望文章能够帮你解决node.js – 如何避免客户端使用redux在react-apollo SSR中重新获取?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。