InstantSearch和服务器端渲染:staticContext未定义

时间:2018-08-01 07:44:46

标签: reactjs react-router algolia serverside-rendering

这是我的服务器端渲染实现...我使用staticContext将道具传递给组件,但在第一个渲染中不起作用...我该如何解决此问题?

这是错误...

my error

我的组件文件...

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>`
        );
    })
})

0 个答案:

没有答案