【问题标题】:Pass data between class Component and function (React)在类组件和函数之间传递数据(React)
【发布时间】:2021-03-13 03:26:57
【问题描述】:

我得到了传递数据的类组件:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class VisitDetails extends Component {
 //...
 render() {
 
 //...
   return() {
      <div>
         {/*pass to function EditVisit.js*/}
        <Link to={{pathname: `/visit/edit/${id}`, state: {data}}}>Edit</Link>
      <div>
   }
 }
}

现在我得到了函数:

import React, { useState } from 'react';
import { useHistory } from "react-router-dom";

function EditVisit (data) {
  console.log(data.info)
 return(
   <div>
    Info: {data.info}
   <div>
 )
}

但是data.info 没有渲染(undefined)。

【问题讨论】:

  • 您在应用程序/代码中使用什么路由/导航包? EditVisit 是一个反应组件,还是只是一个在某处调用的函数?您能否更新您的问题以包括路由在您的应用中的工作原理以及渲染/调用EditVisit 的内容?
  • 我已经添加了我的导入

标签: reactjs react-hooks components parameter-passing


【解决方案1】:

在你的情况下,你可以从道具中读取它

const EditVisit = (props) => {
  const { location: {state: { date }} } = props // date is needed variable from state
  ....
}

screenshot from react-router documentation

【讨论】:

    【解决方案2】:

    使用useLocation react 钩子访问路由状态。

    给定路线

    <Link
      to={{
        pathname: `/visit/edit/${id}`,
        state: { data },
      }}
    >
      Edit
    </Link>
    

    编辑访问

    路由状态可以从location.state.data获取。

    import React, { useState } from 'react';
    import { useHistory, useLocation } from "react-router-dom";
    
    function EditVisit (props) {
      const { state } = useLocation();
      return(
        <div>
         Info: {state.data}
        <div>
      )
    }
    

    为什么不使用useHistory

    History is mutable

    历史对象是可变的。因此建议访问 location 来自&lt;Route&gt; 的渲染道具,而不是来自 history.location。这可以确保你对 React 的假设是 在生命周期钩子中正确。

    【讨论】:

    • 还有一个问题:保存然后使用history.push(/) ?
    • @4est 我不太明白这个问题。
    • @4est 如果您的问题是使用history.push 是否安全,是的,这是用于命令式导航的正确对象。
    • 是的,我想用于导航,再次感谢
    【解决方案3】:

    如果你使用react-router,我认为你应该使用useHistory 钩子和location.state 来捕获React 函数组件中的状态。下面是示例代码。

    import { useHistory } from 'react-router-dom'
    function EditVisit () {
      const history = useHistory()
      const data = history.location.state
     return(
       <div>
        Info: {data.info}
       <div>
     )
    }
    

    您可以在https://levelup.gitconnected.com/how-to-pass-additional-data-while-redirecting-to-different-route-f7bf5f95d48c阅读更多内容

    【讨论】:

    • const data = history.location.state 之后我做了console.log 我看到了数据data: {user: "07M..3", info: "Test", VisitName: "Test2"...} 但返回id 不想显示
    • {data.data.info} 它正在工作,感谢您的帮助
    • @Peter 最好链接官方文档,因为它们可能更准确,但即使您链接的博客也不使用history 对象来访问路由状态。历史是可变的,react-router-dom 建议从 location 对象访问状态,您链接到的博客也是如此。
    猜你喜欢
    • 2022-01-20
    • 2021-10-14
    • 2018-02-15
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多