【问题标题】:Setting initialState in reducer asynchronously在 reducer 中异步设置 initialState
【发布时间】:2017-05-25 01:33:31
【问题描述】:

我有一个反应应用程序,我试图根据从 redis 缓存调用的数据生成路由。

我正在使用https://github.com/ayroblu/ssr-create-react-app-v2

我有一个路由组件,它循环通过 this.props.pages 并像这样创建路由:

class Routes extends Component {

  getRoutes(){
    let container = null;
    const routes = []

    /**
     *  We use a switch statement because the Routes component 
     *  attribute wont take a string so we need to call
     *  the object that we import i.e. HomePage
     */ 
    forEach(this.props.pages, page => {
      switch(page.template){
        case 'home':
          container = HomePage 
          break;
        case 'about':
          container = AboutPage 
          break;
        default:
          throw new Error("No page container matching page's template")
          return;
      }

      routes.push(<Route path={`${page.path}`} component={container} key={key}/>)
    })

    return routes;

  }

  render() {
    return (
      <Switch>
        {this.getRoutes()}
        <Route component={NoMatch}/>
        }
      </Switch>
    )
  }
}

我有一个页面缩减器,它从 redis 缓存中异步获取路由的页面数据,如下所示:

import { SET, RESET } from '../types/page'
import getInitialState from './../../server/initialState'

async function getInitialStateFromCache() {
    const initialState = await getInitialState();

    const {pages} = initialState[0]

    return pages
}

const initialState = getInitialStateFromCache()


export default function reducer(state=initialState, action) {
  switch (action.type) {
    case SET:
      return Object.assign({}, state, action.payload)
    case RESET:
      return {...initialState}
    default:
      return state
  }
}

当在我的路由组件中调用第一个渲染时,this.props.pages 未定义,因此请求的页面 404 是客户端中的第二个渲染,它会出现。这意味着当我查看页面源时,内容还没有被服务器端渲染。

如何延迟第一次渲染,以便在需要时定义 this.props.pages

【问题讨论】:

    标签: javascript node.js reactjs redux react-redux


    【解决方案1】:

    如何延迟第一次渲染,以便在需要时定义 this.props.pages?

    有很多方法可以做到这一点。一种方法是不要立即致电ReactDOM.render。而是:

    • 有一个 index.html 静态显示加载器
    • 应用入口点加载数据
    • 加载数据后,您调用ReactDOM.render

    【讨论】:

      猜你喜欢
      • 2019-09-05
      • 2020-06-07
      • 2020-02-18
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多