简体   繁体   English

ReactJS - 使用来自 Firebase 的数据进行渲染重定向 - “渲染没有返回任何内容”

[英]ReactJS - Render Redirect with data from Firebase - "Nothing was returned from render"

I am fetching an URL from a collection in Firebase linked to an alias field.我正在从链接到别名字段的 Firebase 中的集合中获取 URL。 This part of code is OK, but I can't manage to make a Redirect with the URL field of retrieved data.这部分代码没问题,但我无法使用检索到的数据的 URL 字段进行重定向。 Here is my code:这是我的代码:

import React from 'react'
import { useParams, Redirect } from 'react-router-dom'
import { FirebaseContext } from '../firebase'

function RedirUrl () {
  const { alias } = useParams()
  let link = ''
  const { firebase } = React.useContext(FirebaseContext)
  const dbRef = firebase.db.collection('links')

  function getRedir () {
    dbRef.where('alias', '==', alias).get().then(snapshot => {
      link = snapshot.docs.map(doc => {
        return { ...doc.data() }
      })
      console.log(link[0].longUrl) // it is okay
      return link[0].longUrl
    })
  }
  return <Redirect to={getRedir()} />
}

export default RedirUrl

And here the warning message:这里是警告信息:

Warning: Failed prop type: The prop to is marked as required in Redirect , but its value is undefined警告:道具类型失败:道具toRedirect中标记为必需,但其值undefined

I guess the page is rendering before the retrieved data.我猜页面是在检索到的数据之前呈现的。 Any help is appreciated.任何帮助表示赞赏。

<Redirect to={getRedir()} />

Here you are passing a promise to the to prop, but it should receive a string.在这里,您将 promise 传递给to道具,但它应该收到一个字符串。 You can use useEffect for getting the data from firebase:您可以使用useEffect从 firebase 获取数据:

const { alias } = useParams();
const { link, setLink } = useState('');
const { firebase } = React.useContext(FirebaseContext);
const dbRef = firebase.db.collection('links');

useEffect(() => {
    dbRef
        .where('alias', '==', alias)
        .get()
        .then((snapshot) => {
            const links = snapshot.docs.map((doc) => {
                return { ...doc.data() };
            });
            console.log(links[0].longUrl); // it is okay
            setLink(links[0].longUrl);
        });
}, []);
return link ? <Redirect to={link} /> : <></>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM