这是我的服务器端渲染实现...我使用staticContext将道具传递给组件,但在第一个渲染中不起作用...我该如何解决此问题?
这是错误...
我的组件文件...
class Search extends Component {
render() {
console.log('this.props.staticContext', this.props.staticContext)
return (
<InstantSearch
appId="xx"
apiKey="xx"
indexName="xx"
searchState={this.props.staticContext.searchState}
resultsState={this.props.staticContext.resultsState}
>
<SearchBox />
<Hits hitComponent = {Item}/>
</InstantSearch>
);
}
}
export default { component:Search, findResultsState };
我的server.js文件
const app = express()
app.use(express.static("public"));
app.get('*', async (req, res) => {
const findRoute = matchRoutes(Routes, req.path).filter(({route}) => route.findResultsState)
const promises = findRoute.map(async ({route:{findResultsState, component}}) => {
const searchState = req.query
const resultsState = await findResultsState(component, {searchState})
return {searchState, resultsState}
})
return Promise
.all(promises)
.then(datas => {
const arrayToObject = (array) => array.reduce((obj, item) => {
return item
}, {})
let context = arrayToObject(datas)
const appAsString = renderToString(
<StaticRouter location={req.path} context={context}>
<App />
</StaticRouter>
);
res.send(
`
<!doctype html>
<html>
<body>
<div id="root">${appAsString}</div>
<script>window.__APP_INITIAL_STATE__ = ${JSON.stringify(arrayToObject(datas))}</script>
<script src="/manifest.manifest.js"></script>
<script src="/vendor.bundle.js"></script>
<script src="./app.bundle.js"></script> <!-- this is the build of browser.js -->
</body>
</html>`
);
})
})