【问题标题】:How to pass state to another component using useHistory?如何使用 useHistory 将状态传递给另一个组件?
【发布时间】:2022-01-04 13:06:34
【问题描述】:

我需要将状态从 useState 钩子传递到另一个组件,但它们之间的唯一联系是一个按钮,它具有对历史记录的 onClick 功能。推(路由)。

表格页面(从这个页面我必须将状态发送到下面的 TableMore 页面)

import React, { useState, useEffect } from "react";
import { useTable, usePagination } from "react-table";
import { useHistory } from "react-router-dom";
import styled from "styled-components";
import apiRequest from "helpers/apiRequest";
import Header from "../../../components/Header/Header";

function Table({ columns, data, searchData, setsearchData, getData }) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page, // Instead of using 'rows', we'll use page,
    // which has only the rows for the active page

    // The rest of these things are super handy, too ;)
    canPreviousPage,
    canNextPage,
    nextPage,
    previousPage,
    rows,
  } = useTable(
    {
      columns,
      data,
      searchData,
      setsearchData,
      getData,
      initialState: { pageIndex: 0 },
    },
    usePagination
  );

  // Render the UI for your table
  return (
    <>
      <div className="inputs">
        <Input
          type="text"
          placeholder="Unesi ime "
          onChange={(e) =>
            setsearchData({ ...searchData, ime: e.target.value })
          }
          onKeyPress={(e) => (e.key === "Enter" ? getData() : null)}
        />
        <Input
          type="text"
          placeholder="Unesi ime oca "
          onChange={(e) =>
            setsearchData({ ...searchData, imeOca: e.target.value })
          }
          onKeyPress={(e) => (e.key === "Enter" ? getData() : null)}
        />
        <Input
          type="text"
          placeholder="Unesi prezime "
          onChange={(e) =>
            setsearchData({ ...searchData, prezime: e.target.value })
          }
          onKeyPress={(e) => (e.key === "Enter" ? getData() : null)}
        />
        <Button onClick={() => getData()}>Pretraži</Button>
      </div>
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {page.map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>

      <div className="pagination">
        <span>
          Prikazuje se
          <strong>{rows.length} od 8000</strong> rezultata
        </span>
        <div className="buttons">
          <Button onClick={() => previousPage()} disabled={!canPreviousPage}>
            Prethodna stranica
          </Button>
          <Button onClick={() => nextPage()} disabled={!canNextPage}>
            Sljedeća stranica
          </Button>
        </div>
      </div>
    </>
  );
}

const TablePage = () => {
  const [tableData, setTableData] = useState([]);
  const [searchData, setsearchData] = useState({
    ime: "",
    prezime: "",
    imeOca: "",
  });
  const [data, setData] = useState({
    email: "",
    password: "",
  });
  const [token, setToken] = useState("");
  const [clicked, setClicked] = useState(false);
  const [dataId, setdataId] = useState("");
  const history = useHistory();
  let success = false;
  if (token) {
    success = true;
  } else {
    success = false;
  }

  const getData = async () => {
    const { ime, prezime, imeOca } = searchData;
    try {
      const response = await apiRequest({
        method: "get",
        url: `v1/spisak-srebrenica?prezime=${prezime}&ime=${ime}&imeOca=${imeOca}`,
      });
      if (response.status === 200) {
        setTableData(response.data);
      }
    } catch (err) {
      console.log(err);
    }
  };
  const getToken = async () => {
    await apiRequest({
      method: "post",
      url: `auth/login`,
      data,
    })
      .then((resp) => {
        console.log(resp.data);
        setToken(resp.data.token);
      })
      .catch((err) => {
        console.log(err.response.data);
      });
  };

  useEffect(() => {
    getData();
  }, []);

  const columns = [
    {
      Header: "ID ŽRTVE",
      accessor: "id_grobnog_mjesta",
    },
    {
      Header: "IME (OCA) PREZIME",
      accessor: "ime_prezime",
    },
    {
      Header: "GODINA ROĐENJA",
      accessor: "godina_rodjenja",
    },
    {
      Header: "VIŠE",
      Cell: ({ row }) => (
        <Button
          position="table"
          onClick={() =>
            history.push(`tablemore/${row.values.id_grobnog_mjesta}`) ||
            setClicked(!clicked) ||
            setdataId(row.values.id_grobnog_mjesta)
          }
        >
          više
        </Button>
      ),
    },
  ];
  return (
    <div>
      <Header />
      {success ? (
        <Styles>
          <Table
            columns={columns}
            data={tableData}
            searchData={searchData}
            setsearchData={setsearchData}
            getData={getData}
          />
        </Styles>
      ) : (
        <Container>
          <div className="content">
            <h1>Prijavite se</h1>
            <div className="form">
              <input
                type="email"
                placeholder="Unesite email"
                onChange={(e) => setData({ ...data, email: e.target.value })}
              />
              <input
                type="password"
                placeholder="Unesite šifru"
                onChange={(e) => setData({ ...data, password: e.target.value })}
              />
              <button onClick={getToken}>Prijavi se</button>
            </div>
          </div>
        </Container>
      )}
    </div>
  );
};

export default TablePage;

如您所见,onClick={() => history.push(tablemore/${row.values.id_grobnog_mjesta})} 是我可以调用 tablemore 页面的地方。 所以我不知道如何将 TOKEN 传递给 table more 页面。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    使用react-router-dom v6,您可以将位置状态设置为useNavigate

    import { useNavigate } from "react-router-dom";
    ...
    let navigate = useNavigate();
    navigate("/users/123", { state: partialUser });
    

    使用react-router-dom v5,您可以使用useHistory

    import { useHistory } from "react-router-dom";
    ...
    let history = useHistory();
    history.push("/users/123", { state: partialUser });
    

    在下一页您可以使用useLocation 访问它:

     import { useLocation } from "react-router-dom";
     ...
     let location = useLocation();
     location.state;
    

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 2016-12-05
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 2019-07-17
      • 2019-05-30
      相关资源
      最近更新 更多