按钮无法将数据传递到另一个组件。React

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

Button don't passing data to another component. React

问题

Final Update:

好的,我使用了useLocation钩子成功传递了我的数据。
问题已解决。

英文:

I have a component which is a button. Then in another component i am looping trough concerts and using this button to redirect to booking page but after clicking my data is not passed.

This is my button component:

    import React from "react";

export const BookBtn = (props) => {
  return (
    <div>
      <button
        className="bookBtn"
        style={{ backgroundColor: props.color }}
        // onClick={props.func}
      >
        {props.text}
      </button>
    </div>
  );
};

BookBtn.defaultProps = {
  text: "Unavailable",
};

export default BookBtn;

Here is the button in my main component where I try to click

 <a href={"/concert/" + concert.id} data={concert}>
                  <BookBtn text="Book a ticket" />
                </a>

Here is my component where i try to redirect to and retrive my data.

import React from "react";
import { useEffect, useState } from "react";
import axios from "axios";

export const Book = (data) => {
  const [concerts, setConcerts] = useState([]);
  const [tickets, setTickets] = useState([]);

  useEffect(() => {
    const loadConcerts = async () => {
      const resConcerts = await axios.get("data/concerts");
      const tickets = await axios.get("/data/tickets");
    };
  });
  return (
    <div>
      Booking page
      <h1>{data.name}</h1>
    </div>
  );
};

UPDATE:

I wrapped my button in anchor tag and now i am able to redirect but still can't pass data.

Final Update

Allright, i managed to pass my data using useLocation hook.
Problem is solved.

答案1

得分: 2

我建议使用 react-router 进行重定向或路由,而不是使用锚标签,因为它们会导致页面刷新。

使用 react-router 中的 Link 标签,并将 concert 状态与其一起传递!

查看这个链接 https://reactrouter.com/en/main/components/link

英文:

I'd suggest using react-router to do the redirection or routing instead of anchor tags as they cause a refresh.

Use the Link tag from react-router and pass the concert state along with it!

Have a look at this https://reactrouter.com/en/main/components/link.

huangapple
  • 本文由 发表于 2023年2月14日 21:50:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448803.html
匿名

发表评论

匿名网友

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

确定