以下是我的组件
import React,{Component} from 'react'
import {connect} from 'react-redux'
import {megaNavContent} from '../actions'
class MegaNavComponent extends Component{
constructor(props){
super(props);
this.renderSubCategory = this.renderSubCategory.bind(this);
this.megaNavRender = this.megaNavRender.bind(this);
}
componentDidMount(){
this.props.megaNavContent("Row");
}
megaNavRender(){
var list = [];
const MegaNavData = this.props.content.Row4;
if(MegaNavData != null && MegaNavData.categorie){
const Categories = MegaNavData.categorie
Categories.forEach(function(category){
list.push(
<li>
<a href="#">{category.name}</a>
<ul className="dummy">
<li className="dummy">
<ul className="dl-submenu" id="mob-navi-ul">
<li>
{this.renderSubCategory(category)}
</li>
</ul>
</li>
</ul>
</li>
)
})
}
return list;
}
renderSubCategory(){
var cat = []
console.log("looking for subcategory")
const subCategory = category.data;
subCategory.forEach(function(sub){
cat.push(<ul>{sub}</ul>);
})
return cat;
}
render(){
const MegaNavData = this.props.content.Row;
return(
<div>
<ul className="dl-menu">
{this.megaNavRender()}
</ul>
</div>
);
}
}
function mapStateToProps(state){
return{
content : state.content
}
}
export default connect(mapStateToProps,{megaNavContent})(MegaNavComponent);
从上面的代码中,我想调用renderSubCategory并显示一些HTML / JSX,但是会收到错误。
另外,有没有更好的方法来编写megaNavRender()函数以循环JSON。即forEach(HTML / JSX(forEach(HTML / JSX(forEach(HTML / JSX))))) 而不是为每个forEach循环调用许多回调。
答案 0 :(得分:1)
使用function
关键字声明的Javascript函数有自己的this
上下文,因此this
内的Categories.forEach(function(category){
不会引用该类。您可以使用arrow
语法进行函数声明,这将松散地解析this
的值。变化
Categories.forEach(function(category){
到
Categories.forEach((category) => {