我有一個關于 React 的初學者問題。我剛剛寫了這個組件:
class MovieInput extends React.Component {
constructor(props) {
super(props);
firebase.initializeApp(config);
this.state = {
movies: []
};
}
....
}
它作業正常,將資料保存在 Firebase 中名為電影的集合下。我開始研究第二個組件,如下所示:
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: []
};
}
....
}
設定我的問題的背景可能很有用,也就是說我從本教程中得到啟發開始撰寫上面的代碼。
uj5u.com熱心網友回復:
我不熟悉 firebase 資料庫。
但如果我假設
Firebase.database()
.ref("/")
.set(this.state);
自己處理狀態的不同鍵(如每個值的所有 CRUD 行為)這個簡單的技巧應該適用于你的type道具:
class MediaInput extends React.Component {
constructor(props) {
super(props);
firebase.initializeApp(config);
this.state = {
// The array will have the key 'movies' or 'books'
[props.type]: []
};
}
....
}
但請注意始終定義一個“型別”道具!
uj5u.com熱心網友回復:
首先,我會將 firebase 詳細資訊放入一個單獨的類中以遵守SOLID Dependency Inversion Principle。例如:
class AppDatabase {
constructor() {
firebase.initializeApp(config);
}
addCollection(data) {
return firebase.database().ref('/').set(data);
}
}
其次,我會像你一樣使用 type 道具。
<MediaInput type='movies'/>
<MediaInput type='books'/>
最后,在組件中使用 AppDatabase。例如
import { AppDatabase } from '../services';
class MediaInput extends React.Component {
constructor(props) {
super(props);
this.appDatabase = new AppDatabase();
this.state = {
db: {
[props.type]: []
}
};
}
addCollection() {
this.appDatabase.addCollection(this.state.db);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340274.html
