我目前正在使用 Firebase 和 React 构建一个小型网络应用程序,但我无法从 React 客户端获取 Firebase 中的特定项目。
话虽这么说,我已经习惯了 javascript,其中一个简单的提取可能看起来像这样:
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 的任何好的文档,请随时向我发送链接。
谢谢
最佳答案
诀窍是,您不必像以前那样首先获取所有项目的值。
您应该找到 items
ref,然后查找您想要的子项并使用 .on
或 .once
获取该子项的值。
类似的东西,基于您的示例代码:
componentDidMount() {
firebase.database().ref("items");
.child(this.props.match.params.id)
.once("value")
.then(snapshot => snapshot.val())
.catch(error => ({
errorCode: error.code,
errorMessage: error.message
}));
}
为了更好地理解,让我们看一下原始代码并尝试找出它出错的原因:
componentDidMount(props) {
// ⬇️ this ref points to ALL items
const ref = firebase.database().ref("items");
// ⬇️ here we're asking for the value stored under the above ref
ref.on("value", snapshot => {
let storiesObj = snapshot.val();
/* so firebase gives us what we ask for, storiesObj
* is probably a huge js object with all the items inside.
* And since it's just a regular js object,
* it does not have a `child` method on it, thus calling .child errors out.
*/
storiesObj
.child(this.props.match.params.id)
.then(() => ref.once("value"))
.then(snapshot => snapshot.val())
.catch(error => ({
errorCode: error.code,
errorMessage: error.message
}));
});
}
关于javascript - 在 Firebase 中通过 id 获取特定对象/项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52435658/