首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Uncaught :无法读取空属性(读取“标题”)-- React路由器

Uncaught :无法读取空属性(读取“标题”)-- React路由器
EN

Stack Overflow用户
提问于 2021-12-22 12:47:45
回答 1查看 692关注 0票数 0

我的useLocation of Article.js为我提供了一个null状态,而我将它传递给Article.js中的Link组件。所以我在location.state.titlelocation.state.body上有一个错误。为什么useLocation不检索状态值?

Article.js (我在那里得到我的状态)

代码语言:javascript
复制
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 (我在那里发送我的状态)

代码语言:javascript
复制
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>
    </>
  )
}
EN

Stack Overflow用户

回答已采纳

发布于 2021-12-22 12:59:32

我知道另一种正在起作用的语法:

代码语言:javascript
复制
<Link 
    to={`articles/${item.title
                .replace(/\s+/g, '-')
                .trim()}`}
    state={{
        title: item.title,
        body: item.body,
    }}>
    Lire l'article
</Link>

但是,您必须理解,如果刷新文章页面上的页面,位置状态将为空,因为只有单击链接Lire l'article才会传递状态。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70449295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档