我从Alt搬到了Redux,并决定利用上下文类型。 在混合的某个地方,我的参考文献现在未定义。
使用此代码提供refs的正确程序:
import React, { Component, PropTypes } from 'react';
// components
import TopNavMenuItem from './top-nav-menu-item';
export default class TopNavZone extends Component {
fetchMenu() {
const results = [];
const navItems = this.context.navItems;
navItems.map((item, index) => {
results.push(
<TopNavMenuItem key={ index }
clientId={ this.context.clientInfo._id }
item={ item }
index={ index }
parent={ this.refs.topNavList }
/>
);
});
return results;
}
render() {
return (
<section>
<nav className="top-nav" id="TopNavZone">
<ul ref="topNavList" className="">
{ this.fetchMenu() }
</ul>
</nav>
</section>
);
}
}
TopNavZone.contextTypes = {
navItems: PropTypes.array.isRequired,
clientInfo: PropTypes.object.isRequired
};
谢谢大家。
答案 0 :(得分:0)
我在ComponentDidMount中捕获了ref并使数据成为状态的一部分而不是从render中调用this.fetchMenu函数:
import React, { Component, PropTypes } from 'react';
// components
import TopNavMenuItem from './top-nav-menu-item';
export default class TopNavZone extends Component {
constructor(props) {
super(props); {
this.state = {
results: null
}
}
}
componentDidMount() {
var topNavList = this.refs.topNavList;
this.setState({ results: this.fetchMenu(topNavList) })
}
fetchMenu(topNavList) {
const results = [];
const items = this.context.navItems;
items.map((item, index) => {
results.push(
<TopNavMenuItem key={ index }
clientId={ this.context.clientInfo._id }
item={ item }
index={ index }
parent={ topNavList }
/>
);
});
return results;
}
render() {
return (
<section>
<nav className="top-nav" id="TopNavZone">
<ul ref="topNavList" className="">
{ this.state.results }
</ul>
</nav>
</section>
);
}
}
TopNavZone.contextTypes = {
navItems: PropTypes.array.isRequired,
clientInfo: PropTypes.object.isRequired
};