Сохраните данные своего проекта в состоянии , и вы сможете обновить состояние при добавлении проекта. Таким образом, вы можете .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>
);
};
};