【问题标题】:未捕获的类型错误:无法读取 null 的属性(读取“标题”)-反应路由器
【发布时间】:2022-01-23 16:36:52
【问题描述】:

我的Article.jsuseLocation 让我获得null 状态,而我将它传递给Home.js 中的Link 组件。所以我在location.state.titlelocation.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>
    </>
  )
}

【问题讨论】:

  • 你用的是什么版本的 react-router-dom ?
  • 我使用的是版本 6。
  • 也许您没有在发布的代码中显示它,但我没有看到您将位置发送到商店。在将其检索到其他地方之前,它需要存储

标签: reactjs react-router


【解决方案1】:

我知道另一种有效的语法:

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

但是你必须明白,如果你在文章页面上刷新页面,位置状态将为空,因为只有当你点击链接Lire l'article时,状态才会通过。

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 1970-01-01
    • 2022-06-16
    • 2021-12-01
    • 2022-07-02
    • 2022-06-14
    • 2022-10-23
    • 2015-09-13
    相关资源
    最近更新 更多