我创建了一个网站,它是 React+Redux Serverside Render 应用程序,用于加载服务器数据'不要抓取高度需要的内容。因此,我需要采取一种方法来为 redux 初始状态设置服务器数据,以便它可以打开具有完整内容的 Web 应用程序,但我不知道如何在我的代码中实现这一点。
Store.js
import {createStore, combineReducers} from 'redux'
import {GET_CARDS} from '../actions/cardsAction';
//here is my reducer
function mycards(state={},{type,payload}){
switch(type){
case GET_CARDS : return {data:" test mydata"};
default : return state;
}
}
const allreducer = combineReducers({
cards: mycards
})
export const configurestore=(initState)=>{
const store = createStore(
allreducer,
initState
)
return store;
}
这是我的 Action.js
import dataloader from '../server/dataloader';
export const GET_CARDS ='GET_CARDS';
export function getcards(){
return async (dispatch) =>{
//Dataloader is another module which returns Aws server data it is working fine
let _serverdata = await dataloader()
dispatch({
type:GET_CARDS,
payload:{
data:_serverdata
}
})
}
}
服务器.js
import {Provider} from 'react-redux';
import {configurestore,datasetter} from './store/store';
const port = process.env.PORT || 8080;
const server = express();
..other express code
server.get('*', (req, res, next) => {
const context = {data};
const store = configurestore();
const jsx = (
<Provider store={store}>
<StaticRouter context={context} location={req.url}>
<Template />
</StaticRouter>
</Provider>
);
const reactDom = renderToString(jsx);
res.writeHead( 200, { "Content-Type": "text/html" } );
res.end( htmlTemplate(reactDom,data) );
}).catch(next)
})
function htmlTemplate( reactDom,data ) {
return `basic html code`;
}
这是我的 index.js
import React from "react";
import { hydrate } from "react-dom"
import App from "./client/App";
import { BrowserRouter } from "react-router-dom";
import 'babel-polyfill';
import {Provider} from 'react-redux';
import {configurestore} from './store/store';
const store = configurestore({})
hydrate(
<Provider store={store}>
<BrowserRouter>
<Template />
</BrowserRouter>
</Provider>
,
document.getElementById("app")
)
我的 Component.js
import React, { Component } from 'react';
import {connect} from 'react-redux';
class Home extends Component {
constructor(){
super()
}
render() {
return (
<div>
<h1>Home</h1>
</div>
);
}
}
const mapStateToProps = state =>{
console.log(state,"<<<State in homepage")
return state;
}
export default connect(mapStateToProps)(Home)
我没有得到如何在我在 action.js 中定义的初始状态上设置 Aws 数据,我的组件总是显示我在 index.js 上定义的初始状态并且我无法保持渲染功能,如何解决这个问题。