React.js父组件不能正确呈现子组件

时间:2017-10-06 15:12:32

标签: javascript reactjs

我是ReactJS的新手,但已经遇到了一些我无法解决的问题...

我有一个名为Tree的React组件。该组件必须接收一些数据的数组。必须将此数组中的每个元素呈现为一个名为Department的特殊子组件。

一开始,Tree有州{departments:[]},所以,树必须为空,它是。但后来我改变了Tree的状态,我在部门设置了新的数组,我看不到子元素。

关键是,树的状态确实更新了,并且实际上调用了“render”函数,当我通过部门运行时,我在循环中获得了正确的迭代次数(使用console.log检查)。但仍然没有出现儿童元素。

我的代码有效,我尝试使用固定部门渲染树组件,并在构造函数中将此状态设置为初始状态。树和子组件工作正常。

所以,我无法想象,可能是错的。

这是我的代码,我的班级树

class Tree extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            departments: []
        }
        this.componentDidMount = this.componentDidMount.bind(this);
    }

    componentDidMount() {
       var xhr = new XMLHttpRequest();
       xhr.open('GET', startAdress + '/tutors' + '/getAll', true);
       xhr.send();
       var tree = this;
       xhr.onreadystatechange = function() {
           if (xhr.readyState != 4) return;
           if (xhr.status != 200) {
               alert(xhr.status + ': ' + xhr.statusText);
           } else {
               var newDepts = JSON.parse(xhr.responseText);
               if (Array.isArray(newDepts.content)) {
                   tree.setState({
                       departments: newDepts.content
                   });
               }
           }
       };
   }

   render() {
       var a = this;
       console.log(JSON.stringify(this.state.departments));
       console.log(this.state.departments.length);
       return ( <div className={"Tree"}>
           {
               this.state.departments.forEach(function (department) {
                   console.log("creating branches");
                   return (
                       <Department key={department.name} department={department} />
                   );}
               ) }
           </div> )
   }
}

这是我的儿童部门部门。它使用另一个组件,称为TreeLine,但我认为没有必要把它放在这里。

class Department extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
        }
    }

    render() {
        console.log("department " + JSON.stringify(this.props.department));
        return (
            <div className={'Department'}>
                <TreeLine key={this.props.department.name } classNamePostfix={"Dep"}
                item={this.props.department} />
                {this.props.department.items.forEach(function (item) {
                             return (
                                 <TreeLine key={item.name} classNamePostfix={"Item"}  item={item} />
                            )})
                 }
            </div>
        );
    }
}

提前致谢!

1 个答案:

答案 0 :(得分:1)

而不是.forEach()您应该使用.map()

forEach遍历数组的每个元素并对其执行某些操作,但forEach不会返回任何内容,即使回调返回了某些内容。另一方面,map创建一个新数组,其中回调函数中返回的内容作为该新数组中的元素。

const a = [1,2,3].forEach((i) => {return <span>{i}</span>})
// a = undefined
const b = [1,2,3].map((i) => {return <span>{i}</span>})
// b = [<span>1</span>, <span>2</span>, <span>3</span>]