【问题标题】:TypeError: Cannot read properties of undefined (reading 'state') in reactTypeError:无法在反应中读取未定义(读取“状态”)的属性
【发布时间】:2021-12-21 23:28:05
【问题描述】:

我已经通过Link

将参数传递给了其他组件
{props.posts.map((post)=>{
          return (<>
          
           <tr  >
           <td>{post.title}</td>
           <td class="pull-right"   id="underline"><Link to={{pathname:"/details",state:{title:post.title}}} >Details</Link> </td>
          
       </tr>
       </>)
      })}

但是当我尝试在我的详细信息组件中提取标题的值时,它显示错误。
我的 Details.js 是

import React from 'react'
import { useLocation } from 'react-router-dom';

export default function Details(props) {
    return (
        <div>

            <section class="section">
                <br />
                <section class="details">
                    <h4>Title:{props.location.state.title} </h4>
                    <br />
                    <h4>Categories: </h4><br />
                    <h4>Content: </h4>
                </section>
                <br />
            </section>

        </div>

    )
}

我得到的错误是

TypeError: Cannot read properties of undefined (reading 'state')

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您正在尝试从 props 访问数据,而您已将数据从 Link 组件传递,而不是直接传递给要渲染的组件,要解决此问题,您可以使用 @ 987654322@钩子。 首先创建这个钩子的一个实例。使用创建的实例钻取状态对象。

如果您使用的是react-router-dom v6 及更高版本,则几乎没有进行语法更新。 pathstate 需要作为单独的 props 传递,并且状态属性需要包装在 {} 中。

{props.posts.map((post)=>{
          return (<>
          
           <tr  >
           <td>{post.title}</td>
           <td class="pull-right" id="underline"><Link to={"/details"} state={{title:post.title}}>Details</Link> </td>
          
       </tr>
       </>)
      })}

MyDetails.js

import React from 'react'
import { useLocation } from 'react-router-dom';

export default function Details(props) {
    const location = useLocation() //Instance of useLocation hook.
    return (
        <div>

            <section class="section">
                <br />
                <section class="details">
                    <h4>Title:{location.state.title} </h4> 
                    <br />
                    <h4>Categories: </h4><br />
                    <h4>Content: </h4>
                </section>
                <br />
            </section>

        </div>

    )
}

【讨论】:

  • 现在出现这个错误TypeError: Cannot read properties of null (reading 'title')
  • 你能console.log, location.state 看看打印的是什么吗?
  • 它正在打印'null'
  • 您使用的是哪个版本的react-router
  • react-router-dom@6.1.1
猜你喜欢
  • 1970-01-01
  • 2021-11-18
  • 2022-09-27
  • 2019-07-25
  • 2021-12-02
  • 1970-01-01
  • 2020-06-17
相关资源
最近更新 更多