您可以使用context,例如:
import React, { Component, PropTypes, Children } from 'react'
class Provider extends Component {
static childContextTypes = {
isAuthed: PropTypes.bool
}
constructor(props) {
super(props);
this.initialData = isClient ? window.__initialData__ : props.initialData;
}
getChildContext() {
return {
isAuthed: this.initialData.isAuthed
};
}
render() {
let { children } = this.props;
return Children.only(children);
}
}
并包装:
// The server creates this object:
const initialData = {
isAuthed: true
};
if (IS_CLIENT) {
ReactDOM.render(
<Provider>
<Router history={createHistory()}>{Routes}</Router>
</Provider>,
document.getElementById('app')
);
}
if (IS_SERVER) {
// Using renderToStaticMarkup/renderToString etc on:
<Provider initialData={initialData}>
<RoutingContext {...renderProps} />
</Provider>
}
然后,您可以从任何组件在服务器或客户端上访问它:
import React, { Component, PropTypes } from 'react'
class SomeComponent extends Component {
static contextTypes = {
isAuthed: PropTypes.bool
}
constructor(props, context) {
super(props, context);
console.log(context.isAuthed); // this.context outside ctor
}
}
简单的客户端检查类似 typeof document !== 'undefined'