【发布时间】:2021-12-13 10:38:12
【问题描述】:
我有一个关于 React 的初学者问题。我刚刚写了这个组件:
class MovieInput extends React.Component {
constructor(props) {
super(props);
firebase.initializeApp(config);
this.state = {
movies: []
};
}
....
}
它工作正常,将数据保存在 Firebase 中的一个名为 movies 的集合下。 我开始研究第二个组件,如下所示:
class BookInput extends React.Component {
constructor(props) {
super(props);
firebase.initializeApp(config);
this.state = {
books: []
};
}
....
}
我已经可以看到,这两个组件的大部分代码将是相同的,因此编写两次毫无意义。所以问题来了。我怎样才能编写一个标准组件,使用我可以传递的道具,并有类似的东西:
<MediaInput type='movies'/>
<MediaInput type='books'/>
代替:
<MovieInput />
<BookInput />
新组件可能如下所示:
class MediaInput extends React.Component {
constructor(props) {
super(props);
firebase.initializeApp(config);
this.state = {
// Make use of some prop to set collection adequately ....
// This is what I don't know how to do ....
collection: []
};
}
....
}
设置我的问题的背景可能很有用,说我受到this tutorial 的启发开始编写上面的代码。
........ 再做一些工作:
我正在尝试实现一个更通用的组件 (MediaInput)(如 srgbnd 的回答中所建议的那样)。我通过修改 MovieInput 中的代码来做到这一点(已经工作)。我在实现上仍然遇到了一些问题:
componentDidUpdate(prevProps, prevState) {
//if (prevState !== this.state) { // This line may need to be modified to the following.
if (prevState.db !== this.state.db) {
this.writeUserData();
}
}
writeUserData = () => {
firebase.database()
.ref("/")
.set(this.state);
};
handleSubmit = event => {
event.preventDefault();
.....
// These 3 lines should be modified. Probably replacing movies by something like state.db.{props.type} ???
const { movies } = this.state;
movies.push({ ... });
this.setState({ movies });
.....
};
【问题讨论】:
标签: reactjs firebase firebase-realtime-database