【发布时间】:2018-10-31 14:25:44
【问题描述】:
我正在关注本教程:https://crypt.codemancers.com/posts/2017-06-03-reactjs-server-side-rendering-with-router-v4-and-redux/,我认为这是在 react (?) 中进行服务器端渲染的“标准”方式。
基本上发生的事情是我使用反应路由器(v4)来制作所有即将渲染的组件的树:
const promises = branch.map(({ route }) => {
return route.component.fetchInitialData
? route.component.fetchInitialData(store.dispatch)
: Promise.resolve();
});
等待所有这些承诺解决,然后致电renderToString。
在我的组件中,我有一个名为 fetchInitialData 的静态函数,如下所示:
class Users extends React.Component {
static fetchInitialData(dispatch) {
return dispatch(getUsers());
}
componentDidMount() {
this.props.getUsers();
}
render() {
...
}
}
export default connect((state) => {
return { users: state.users };
}, (dispatch) => {
return bindActionCreators({ getUsers }, dispatch);
})(Users);
除了在服务器和客户端都调用getUsers之外,所有这些都很好。
我当然可以检查是否有任何用户已加载并且不在componentDidMount 中调用getUsers,但必须有更好、更明确的方法来不进行两次异步调用。
【问题讨论】:
标签: javascript reactjs react-router react-redux react-ssr