我正在使用子Context技术将上下文传递给应用程序的子代。
子上下文成功传递到 标题组件 ,但未在 Encounter组件 上传递。 有任何想法来解决这个问题。 感谢。
应用:
export default class Application extends React.Component {
constructor(props, context){
super(props);
this._onDataReceived=this._onDataReceived.bind(this);
}
componentDidMount() {
PersonalStore._onDataReceived(this._onDataReceived);
}
componentWillUnmount() {
PersonalStore._offDataReceived(this._onDataReceived);
}
getChildContext() {
return { name:"Moussawi7" };
}
renderRouter(){
ReactDOM.render((
<Router>
<Route path="/" component={Encounter} />
<Route path="inbox">
<IndexRoute component={Inbox} onEnter={()=>this.refreshScroller()}/>
<Route path=":userID" component={Conversation} />
</Route>
<Route path="*" component={NotFound} />
</Router>
),document.getElementById('content'));
}
render() {
return (
<div className="container">
<Header/>
<div id="content"></div>
</div>
);
}
_onDataReceived() {
this.renderRouter();
}
}
Application.childContextTypes={
name: React.PropTypes.string.isRequired
}
部首:
export default class Header extends React.Component {
constructor(props,context) {
super(props,context);
console.log(context);// Object{name:"Moussawi7"}
}
}
Header.contextTypes= {
name: React.PropTypes.string.isRequired
}
遭遇:
export default class Encounter extends React.Component {
constructor(props,context) {
super(props,context);
console.log(context);// Object {name:undefined}
}
}
Encounter.contextTypes= {
name: React.PropTypes.string.isRequired
}
答案 0 :(得分:6)
正如莫豪斯所说,这可能是你的问题。建议的方法是路由器是基本元素,而Application包装其他路由。在这里,我将Provider包装在路由器周围,以便所有东西都可以访问Provider的上下文:
// Provider.js Your app context provider
import React, { Component, PropTypes, Children } from 'react'
class Provider extends Component {
static childContextTypes = {
name: PropTypes.string
}
getChildContext() {
return {
name: 'Moussawi7'
};
}
render() {
let { children } = this.props;
return Children.only(children);
}
}
// Router.js Your Provider+Router is the first thing rendered on the root, not Application, which is the base route
ReactDOM.render(
<Provider>
<Router>
<Route path='/' component={Application}>
<IndexRoute component={Encounter} />
<Route path='users' component={Users} />
<Route path="inbox">
<IndexRoute component={Inbox} onEnter={()=>this.refreshScroller()}/>
<Route path=":userID" component={Conversation} />
</Route>
<Route path="*" component={NotFound} />
</Route>
</Router>
</Provider>,
document.getElementById('content')
);
// Your Application renders the child routes
class Application extends Component {
render() {
return (
<div>
<header>
<nav>
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/users'>Users</Link></li>
</ul>
</nav>
</header>
<div className='route-content'>
{this.props.children}
</div>
</div>
)
}
}
注意我在那些需要babel阶段0的例子中使用了es7&#39; static
我相信,但你可以把它们放在课外。