我试图让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任何想法?
将项目数据存储在state中,您可以在添加项目时更新状态。这样,你可以在渲染函数中使用.map()
状态,当你添加项目时,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>
);
};
};