[英]How To Query Firestore to get Document by String Field (Search Engine Friendly Slug)
我在React中有一個名為ShowArticle
的組件,我正在嘗試通過名為slug的字符串字段在我的articles
集中的Firestore
中查詢單個文檔,以便可以將URL設置為//myhost.com/article/show/:slug
slug是Firestore中匹配的唯一字符串。
作為路線,我有:
<Route exact path="/article/show/:slug" component={ShowArticle} />
所以我用const { slug } = props.match.params;
正確獲取了:slug
參數const { slug } = props.match.params;
在ShowArticle
組件內部。
當我向Firestore查詢數據庫中存在的塊時,我沒有收到來自Firestore的數據。
如何通過SEF URL的唯一字符串值檢索文章文檔?
我的ShowArticle組件如下:
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { firestoreConnect } from 'react-redux-firebase'; import { PropTypes } from 'prop-types'; import Article from "./Article"; class ShowArticle extends Component { render() { const { article } = this.props; if (article) { return ( <div> <Article key={article.id} title={article.title} date={article.date} body={article.body} /> </div> ); } else { return ( <div>Loading...</div> ) } } } ShowArticle.propTypes = { firestore: PropTypes.object.isRequired }; export default compose( firestoreConnect(props => { const { slug } = props.match.params; console.log(slug); return [ {collection: 'articles', storeAs: 'article', doc: slug } ] }), connect(({ firestore: { ordered } }, props) => ({ article: ordered.article && ordered.article[0] })) )(ShowArticle);
在firestoreConnect()
的回調中,將doc: slug
更改為queryParams: [ 'equalTo=' + slug ]
因此,您將得到:
export default compose(
firestoreConnect(props => {
const { slug } = props.match.params;
console.log(slug);
return [
{collection: 'articles', storeAs: 'article', queryParams: [ 'equalTo=' + slug ] }
]
}),
connect(({ firestore: { ordered } }, props) => ({
article: ordered.article && ordered.article[0]
}))
)(ShowArticle);
請參考文檔中有關react-redux-firebase
軟件包的http://react-redux-firebase.com/docs/queries.html#notPars 。
很可能您正在使用最新版本的React Router(v4 +)。 因為在較舊的React Router中,這是使ID與道具一起可用的方法。 但是在更新的react-router庫中,您必須使用“ withRouter”高階組件包裝整個組件。 每當渲染時,它將更新的匹配,位置和歷史道具傳遞給包裝的組件。
首先,您必須導入withRouter。
import { withRouter } from "react-router";
然后,您必須使用withRouter包裝它。
export default withRouter(compose(
firestoreConnect(props => {
const { slug } = props.match.params;
console.log(slug);
return [
{collection: 'articles', storeAs: 'article', doc: slug }
]
}),
connect(({ firestore: { ordered } }, props) => ({
article: ordered.article && ordered.article[0]
}))
)(ShowArticle))
這對我來說就像一種魅力!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.