我的useLocation of Article.js为我提供了一个null状态,而我将它传递给Article.js中的Link组件。所以我在location.state.title和location.state.body上有一个错误。为什么useLocation不检索状态值?
Article.js (我在那里得到我的状态)
import React from 'react';
import {useLocation} from 'react-router-dom';
import './Article.css';
export default function Article()
{
const location = useLocation()
console.log(location);
return (
<div className='article-content'>
<h2>Votre article: {location.state.title}</h2>
<p>{location.state.body}</p>
</div>
)
}Home.js (我在那里发送我的状态)
import React from 'react';
import './Home.css';
import Card from '../../Components/Card/Card';
import {useSelector, useDispatch} from 'react-redux';
import {useEffect, useState} from 'react';
import {getArticles} from '../../redux/articles/articleReducer';
import {v4 as uuidv4} from 'uuid';
import {Link} from 'react-router-dom';
export default function Home()
{
const {articles} = useSelector(state => (
{
...state.articleReducer
}));
const dispatch = useDispatch();
useEffect(() =>
{
if (articles.length === 0)
{
dispatch(getArticles());
}
}, [])
return (
<>
<h1 className='home-title'>Tous les articles</h1>
<div className="container-cards">
{articles.map(item =>
{
console.log(item.title);
console.log(item.body);
return(
<Card key={uuidv4()}>
<h2>{item.title}</h2>
<Link to={{
pathname: `articles/${item.title
.replace(/\s+/g, '-')
.trim()}`,
state: {
title: item.title,
body: item.body,
},
}}
>
Lire l'article
</Link>
</Card>
);
})}
</div>
</>
)
}发布于 2021-12-22 12:59:32
我知道另一种正在起作用的语法:
<Link
to={`articles/${item.title
.replace(/\s+/g, '-')
.trim()}`}
state={{
title: item.title,
body: item.body,
}}>
Lire l'article
</Link>但是,您必须理解,如果刷新文章页面上的页面,位置状态将为空,因为只有单击链接Lire l'article才会传递状态。
https://stackoverflow.com/questions/70449295
复制相似问题