在渲染服务器端之前获取数据

时间:2015-06-22 07:15:01

标签: javascript reactjs fetch react-router isomorphism

现在我发现了 Este.js ,我对同构应用程序有一点问题。在使用renderToString()渲染服务器端之前,我不了解如何进行api调用。

一种解决方案是使用React Router在路由器级别进行所有数据提取。根据顶级路由,我可以预测需要哪些数据,进行api调用,然后调用React.renderToString。

很好,但我仍然需要在组件级别和路由器级别声明数据依赖性。我最后两次编写相同的代码,我不相信这是最好的方法。

编辑:好的,现在我能够按照自己的意愿做点什么。使用React-Router和link我已经能够做到以下几点:

给出这个全局应用程序状态,我想在指向/ todos

时预取todos

initialstate.js

{
  auth: {
    data: null,
    form: null
  },
  examples: {
    editable: {
      state: null,
      text: 'Some inline-editable text.'
    }
  },
  i18n: {
    formats: {},
    locales: initialLocale,
    messages: messages[initialLocale]
  },
  pendingActions: {},
  todos: {
    editables: {},
    newTodo: {
      title: ''
    },
    list: [{
      id: 1,
      title: 'first todo yipiyo'
    }]
  },
  users: {
    viewer: null
  }
}

todos.react.js

在todo组件中,我声明了一个静态函数fetchData。因为我想要在我的appState中检索正确的密钥,所以我会通过' list'作为一个参数。感觉很脏。

class Todos extends Component {

  static fetchData(){
    return actions.loadAllTodos('list');
  }

  componentDidMount(){
    Todos.fetchData();
  }

  render() {
    ...
  }

}

actions.js

Api电话和东西,我将钥匙传递给承诺 - 感觉hacky

export function loadAllTodos(key) {

  const promise = new Promise((resolve, reject) => {

    Api.get()
    .then(res => {
      res.key = key; //hacky time
      resolve(res)
    })
    .catch(err => {
      reject(err);
    })

  });

  return dispatch(loadAllTodos, promise);

}

render.js

router.run((Handler, routerState) => {

  var promise = Promise.all(routerState.routes
        .filter(route => route.handler.fetchData)
        .map(route => {
          return route.handler.fetchData();
        })
      );

  promise.then(resp => {

    console.log(resp);

    //Displays : 
    [ { id: 2, title: 'Im a second todo' },{ id: 3, title: 'I like todo' },
    cursor: 'list' ]

    //Some stuff to add resp to appState, using the correct key, yey iso+api=win
    appState = mergeThisWithMagic(appState, resp);

    const html = preloadAppStateThenRenderHtml(Handler, appState);
    const notFound = routerState.routes.some(route => route.name ===
      'not-found');
    const status = notFound ? 404 : 200;
    res.status(status).send(html);
    resolve();

  });


});

如您所见,我将创建一个函数来使用更新的todoList更新appState。

这可以做到这一切吗?我想得到一些反馈,因为我觉得我走的是一条黑暗的道路:(。

1 个答案:

答案 0 :(得分:2)

我在我的同构服务器端应用程序中完成了这个操作,方法是将我的fetchData函数放在组件的statics对象中,并使用promises等待所有数据返回后再将应用程序渲染为字符串。

然后,您将通过props将返回的数据传递给渲染的组件。这个例子有助于我开发这个应用程序。 React Router Mega Demo

相关问题