无法通过React路由传递信息至链接。

huangapple go评论56阅读模式
英文:

Not able to Pass information throught link in react route

问题

I'm not able to pass information using props through link in react route. I tried to pass the current contact got through a component in the contact card and passing the same prop to contact details but I'm not able to fetch the object sent by me in the contact details getting undefined when consoling the props.

import React, { useState } from 'react';
import user from "../images/user.png";
import { Link } from "react-router-dom";

function ContactCard(props) {
  const [data, setData] = useState(props.contact)
  const { id, name, email, mobile } = props.contact;

  return (
    <div>
      <div className="item">
        <div className="ui avtar image">
          <img src={user} alt="user" />
        </div>
        <div className="content">
          <Link to={{ pathname: `/contact/${id}`, state: { data: data }}}>
            <div className="header">{name}</div>
            <div>{email}</div>
            <div>{mobile}</div>
          </Link>
        </div>
        <i
          className="trash alternate outline icon"
          style={{ color: 'red', marginTop: '7px' }}
          onClick={() => props.clickHandler(id)}
        ></i>
      </div>
    </div>
  );
}

export default ContactCard;
import React from 'react';
import { useLocation } from 'react-router-dom';
import user from "../images/user.png";

function ContactDetails(props) {
    const location = useLocation();
    console.log(props, "props");
    const data = location.state?.data;
    console.log(data);

  return (
    <div className="main">
      <div className="ui card centered">
        <div className="image">
          <img src={user} alt="user" />
        </div>
        <div className="content">
          <div className="header">name</div>
          <div className="description">email</div>
          <div className="description">mobile</div>
        </div>
      </div>
    </div>
  );
}

export default ContactDetails;
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { v4 as uuid } from "uuid";
import './App.css';
import Header from "./Header";
import AddContact from "./AddContact";
import ContactList from "./Contactlist";
import ContactDetails from "./ContactDetails";

function App() {
  const LOCAL_STORAGE_KEY = "contacts";

  const [contacts, setContacts] = useState(
    JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || []
  );

  const addHandler = (contact) => {
    console.log(contact);
    setContacts([...contacts, { id: uuid(), ...contact }]);
  };

  const removeContactHandler = (id) => {
    const newContactList = contacts.filter((contact) => {
      return contact.id !== id;
    });

    setContacts(newContactList);
  }

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  }, [contacts]);

  return (
    <div className="ui container">
      <Router>
        <Header />
        <div className="content">
          <Routes>
            <Route path="/" element={<ContactList contacts={contacts} getContactId={removeContactHandler} />} />
            <Route path="/add" element={<AddContact addHandler={addHandler} />} />
            <Route
              path="/contact/:id"
              element={<ContactDetails/>}
            />
          </Routes>
        </div>
      </Router>
    </div>
  );
}

export default App;

Please note that I've corrected the code formatting issues.

英文:

I'm not able to pass information using props through link in react route. I tried to pass the current contact got through a component in the contact card and passing the same prop to contact details but I'm not able to fetch the object sent by me in the contact details getting undefined when consoling the props.

import React, { useState } from &#39;react&#39;;
import user from &quot;../images/user.png&quot;;
import { Link } from &quot;react-router-dom&quot;;

function ContactCard(props) {
  const [data, setData] = useState(props.contact)
  const { id, name, email, mobile } = props.contact;

  return (
    &lt;div&gt;
      &lt;div className=&quot;item&quot;&gt;
        &lt;div className=&quot;ui avtar image&quot;&gt;
          &lt;img src={user} alt=&quot;user&quot; /&gt;
        &lt;/div&gt;
        &lt;div className=&quot;content&quot;&gt;
          &lt;Link to={{ pathname: `/contact/${id}`, state: { data: data }}}&gt;
            &lt;div className=&quot;header&quot;&gt;{name}&lt;/div&gt;
            &lt;div&gt;{email}&lt;/div&gt;
            &lt;div&gt;{mobile}&lt;/div&gt;
          &lt;/Link&gt;
        &lt;/div&gt;
        &lt;i
          className=&quot;trash alternate outline icon&quot;
          style={{ color: &#39;red&#39;, marginTop: &#39;7px&#39; }}
          onClick={() =&gt; props.clickHandler(id)}
        &gt;&lt;/i&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

export default ContactCard;
import React from &#39;react&#39;;
import { useLocation } from &#39;react-router-dom&#39;;
import user from &quot;../images/user.png&quot;;

function ContactDetails(props) {
    const location = useLocation();
    console.log(props, &quot;props&quot;);
    const data = location.state?.data;
    console.log(data);
//   const { contact } = props.location.state;
//   const { id, name, email, mobile } = contact;

  return (
    &lt;div className=&quot;main&quot;&gt;
      &lt;div className=&quot;ui card centered&quot;&gt;
        &lt;div className=&quot;image&quot;&gt;
          &lt;img src={user} alt=&quot;user&quot; /&gt;
        &lt;/div&gt;
        &lt;div className=&quot;content&quot;&gt;
          &lt;div className=&quot;header&quot;&gt;name&lt;/div&gt;
          &lt;div className=&quot;description&quot;&gt;email&lt;/div&gt;
          &lt;div className=&quot;description&quot;&gt;mobile&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

export default ContactDetails;
import React, { useState, useEffect } from &quot;react&quot;;
import { BrowserRouter as Router, Routes, Route } from &#39;react-router-dom&#39;;
import { v4 as uuid } from &quot;uuid&quot;;
import &#39;./App.css&#39;;
import Header from &quot;./Header&quot;;
import AddContact from &quot;./AddContact&quot;;
import ContactList from &quot;./Contactlist&quot;;
import ContactDetails from &quot;./ContactDetails&quot;;

function App() {
  const LOCAL_STORAGE_KEY = &quot;contacts&quot;;

  const [contacts, setContacts] = useState(
    JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || []
  );

  const addHandler = (contact) =&gt; {
    console.log(contact);
    setContacts([...contacts, { id: uuid(), ...contact }]);
  };

  const removeContactHandler = (id) =&gt; {
    const newContactList = contacts.filter((contact) =&gt; {
      return contact.id !== id;
    });

    setContacts(newContactList);
  }

  useEffect(() =&gt; {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
  }, [contacts]);

  return (
    &lt;div className=&quot;ui container&quot;&gt;
      &lt;Router&gt;
        &lt;Header /&gt;
        &lt;div className=&quot;content&quot;&gt;
          &lt;Routes&gt;
            &lt;Route path=&quot;/&quot; element={&lt;ContactList contacts={contacts} getContactId={removeContactHandler} /&gt;} /&gt;
            &lt;Route path=&quot;/add&quot; element={&lt;AddContact addHandler={addHandler} /&gt;} /&gt;
            &lt;Route
              path=&quot;/contact/:id&quot;
              element={&lt;ContactDetails/&gt;}
            /&gt;
          &lt;/Routes&gt;
        &lt;/div&gt;
      &lt;/Router&gt;
    &lt;/div&gt;
  );
}

export default App;

答案1

得分: 3

ContactDetails中,你正在将props记录到控制台,但组件只传递了location,所以propsundefined。<br>

在这里你传递了props

&lt;ContactList 
  contacts={contacts} 
  getContactId={removeContactHandler} 
/&gt;

在这里没有传递props

&lt;ContactDetails/&gt;

还有,如其他答案中所提到的,据我所知,这是正确的语法:

&lt;Link to={`/contact/${id}`} state={{ data }}&gt;&lt;/Link&gt;
英文:

In ContactDetails, you are logging props to the console, but there is no props passed to the component but only location that's why props is undefined.<br>

here you are passing props :

&lt;ContactList 
  contacts={contacts} 
  getContactId={removeContactHandler} 
/&gt;

here not:

&lt;ContactDetails/&gt;

also as mentioned in the other answer, as far as I know this is the correct syntax:

&lt;Link to={`/contact/${id}`} state={{ data }}&gt;&lt;/Link&gt;

答案2

得分: 1

也许你应该尝试通过以下方式将所需的值传递给 <Link></Link>

<Link to={} state={{ data: data }}></Link>

看起来你把 state 属性放在了 to 属性的值中。无论如何,请告诉我们是否更改有效。祝你好运!

英文:

Maybe you should try passing the required value through the &lt;Link&gt;&lt;/Link&gt; in the following manner:

&lt;Link to={} state={{ data: data }}&gt;&lt;/Link&gt;

It appears that you've placed the state prop within the to prop's value. In any case do let us know whether or not the change worked. Good luck!

huangapple
  • 本文由 发表于 2023年7月6日 17:02:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定