从react方法中返回组件

时间:2018-09-10 14:16:11

标签: javascript reactjs firebase

我试图让React从另一个组件的方法内返回一个组件。到目前为止,我有:

export class Projects extends Component {
    constructor() {
        super();
        this.loadProjects = this.loadProjects.bind(this);
    }

    loadProjects() {
        var userProjectsRef = dbroot.child("users").child(this.props.user.uid).child("projects").ref;
        userProjectsRef.on("child_added", function(snapshot) {
            var id = snapshot.val();
            return (
                <ProjectsRow projectId={id} />
            );
        })
    }

    render() {
        return (
            <div className="container">
                <div className="card">
                    <div className="card-header bg-dark text-light align-center">
                    </div>
                    <ul className="list-group list-group-flush align-left">
                        {this.loadProjects()}
                    </ul>
                </div>
                <AddProjectModal user={this.props.user} />
            </div>
        );
    };
};

我不确定为什么loadProjects方法中的return语句不起作用。但是,它可以在同一位置返回console.log语句。我还引用了此堆栈溢出问题:React. Creating a function that returns html 有任何想法吗?

1 个答案:

答案 0 :(得分:0)

将项目数据存储在state中,然后可以在添加项目时更新状态。这样,您可以.map()在render函数中的状态,当您添加项目时,React将自动保持调用状态。

export class Projects extends Component {
    constructor() {
        super();

        // set initial empty state
        this.state = {
          projects : []
        };
    }

    // do the state manipulation after the component has mounted
    componentDidMount() {
        var userProjectsRef = dbroot.child("users").child(this.props.user.uid).child("projects").ref;
        userProjectsRef.on("child_added", function(snapshot) {
            var id = snapshot.val();
            const newProject = {id :id};

            // update the state and add the new project
            this.setState((prevState) => ({
              ...prevState, // not needed in this trivial example but would be needed if the state stored other things because setState overwrites the whole state
              projects : [...prevState.projects, newProject] // the updated project is array is the existing array with the new one appended
            }));
        }.bind(this)); // bind this context because the function creates its own this context (or switch to an arrow function)
    }

    // map this.state.projects to <ProjectsRow> components
    render() {
        return (
            <div className="container">
                <div className="card">
                    <div className="card-header bg-dark text-light align-center">
                    </div>
                    <ul className="list-group list-group-flush align-left">
                        {this.state.projects.map((project, index) => <ProjectsRow key={index} projectId={project.id} />)}
                    </ul>
                </div>
                <AddProjectModal user={this.props.user} />
            </div>
        );
    };
};