【发布时间】:2021-07-20 19:08:10
【问题描述】:
我正在尝试将博客呈现为卡片,然后将其作为页面打开,但事实证明使用 Gatsby 很难。我使用 React 路由器做出了完全相同的反应,但它似乎不适用于 Gatsby。我知道我可以使用 GraphQL,但我当然可以使用 REST 做同样的事情。我正在使用内容丰富的顺便说一句
我按照另一篇文章中的建议切换到路由器,但这不起作用。
我在使用 react-router-dom 时不断收到此错误:
Invariant failed: You should not use <Link> outside a <Router>
获取博客内容
function Blog() {
const [blogs, setBlogs] = useState([])
const [image, setImage] = useState()
const [selectedBlog, setSelectedBlog] = useState(blogs)
useEffect(() => {
fetch("http://cdn.contentful.com...")
.then(response => response.json())
.then(data =>
setBlogs(data.items)
)
}, [])
console.log(blogs)
return (
<>
<div className="card-flex" >
{selectedBlog !== null ? blogs.map((blog =>
<Card title={blog.fields.title} date={blog.fields.date} introduction={blog.fields.introduction} mainBody1={blog.fields.mainBody1} mainBody2={blog.fields.mainBody2} setSelectedBlog={selectedBlog}
/>
)):
<Article title={blogs.find(d => d.fields.title === selectedBlog)} />
}
</div>
</>
)
}
export default Blog
博客卡片
function Card(props) {
console.log(props)
return (
<div class="container">
<div class="card">
<div class="card-header">
<img style={{backgroundImage: "url('https://i.pinimg.com/564x/7f/bb/97/7fbb9793b574c32f5d28cae0ea5c557f.jpg')"}}/>
</div>
<div class="card-body">
<span class="tag tag-teal">{props.tags}</span>
<h4>{props.title}</h4>
<p style={{fontSize:"17px", paddingTop:"10px"}} >{props.introduction}</p>
<div class="card-user">
<Link
to={{
pathname: '/article',
state: {
title: props.title,
introduction: props.introduction
}
}}
>
<button>read more</button>
</Link>
<div class="user-info">
<h5 >{ props.date}</h5>
</div>
</div>
</div>
</div>
</div>
)
}
export default Card
**文章**
import React from 'react'
import './Article.css'
import { useLocation } from "@reach/router"
function Article(props) {
// useLocation to access the route state from Blog.js
const { state = {} } = useLocation();
console.log(state)
return (
<div className="main">
<h1 className="title">{state.title}</h1>
<p className="intro">{state.introduction}</p>
<p className="main1">{state.mainBody1}</p>
<p className="main2">{state.mainBody2}</p>
</div>
)
}
export default Article
【问题讨论】:
-
对于这个错误“Invariant failed: You should not use outside a
”,你只是缺少 例如:` , example 2: ` -
试过了,不行。它现在给我一个 404 错误,并且不会将我重定向到文章页面
-
也就是说,您的路由 URL 现在有错误...所以第一个问题解决了,第二个问题检查您的 URL 和您在
中的路径 -
url 是正确的,因为它在 pages 文件夹中。当我将它移动到页面文件夹
时出现此错误: 上找不到的子项必须具有 path或default属性,或者是<Redirect>。在元素类型[object Object] -
我用 React 和 React Router 做了同样的事情,它工作得很好,我不知道为什么它不能和 Gatsby 一起工作。我也使用相同的 useLocation 并向链接提供状态
标签: javascript reactjs gatsby contentful contentful-api