【发布时间】:2018-09-21 02:09:57
【问题描述】:
我目前正在使用 Firebase 和 React 构建一个小型 Web 应用程序,但我无法从 React 客户端获取 Firebase 中的特定项目。
话虽如此,我已经习惯了 javascript,其中一个简单的 fetch 可能看起来像:
const url = 'www.example.com/api/'
const id = '123'
fetch(url + id) <---specific
.then(res => res.json())
.then(result => this.setState({results: result})
.catch(err => console.log(err))
但是,我找不到任何与 firebase 相似的文档。
以下更具体的问题:
class StoryItem extends Component {
constructor(props) {
super(props);
this.state = {
story: this.props.location.myCustomProps
};
}
componentDidMount() {
//this should do a fetch request based on the
//params id to get the specific item in the firebase
//right now it is being passed as prop which is unreliable because when page refresh state is reset
//user should be able to access content
//without having to go to previous page
console.log(this.state.story)
}
我尝试从 firebase 获取特定对象的一种方法是:
componentDidMount(props) {
const ref = firebase.database().ref("items");
ref.on("value", snapshot => {
let storiesObj = snapshot.val();
storiesObj
.child(this.props.match.params.id)
.then(() => ref.once("value"))
.then(snapshot => snapshot.val())
.catch(error => ({
errorCode: error.code,
errorMessage: error.message
}));
});
}
任何帮助将不胜感激,另外,如果有人知道有关 firebase 的任何好的文档,请随时给我发送链接。
谢谢
【问题讨论】:
标签: javascript reactjs firebase firebase-realtime-database