我有两页:(Datatable.jsx和Single.jsx).

我需要将id从Datatable.jsx发送到Single.jsx.在谷歌搜索之后,我found知道我可以使用<Link />组件来做到这一点,如下所示:

<Link
  to={{
    pathname: "/page",
    state: data
  }}
>

然后您可以访问所需的发送data到第二页:

render() {
  const { state } = this.props.location
  return (
    // render logic here
  )
}

我不知道如何在我的两个页面上应用这个:

Datable.jsx:

//...

const Datatable = () => {
  const [data, setData] = useState([]);

  const handleDelete = (id) => {
    setData(data.filter((item) => item.id !== id));
    fetch(`https://api.factarni.tn/article/${id}`, {
      method: "DELETE",
      headers: {
        Authorization:
          "Bearer eyJhbGciOiJS...qw2QWltkyA",
      },
    }).then((response) => response.json());
  };

  useEffect(() => {
    fetch("https://api.factarni.tn/article", {
      method: "GET",
      headers: {
        Authorization:
          "Bearer eyJhbGciOiJSUz...WltkyA",
      },
    })
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  const actionColumn = [
    {
      field: "action",
      headerName: "Action",
      width: 200,
      renderCell: (params) => {
        return (
          <div className="cellAction">
            <Link to="/users/test" style={{ textDecoration: "none" }}>
              <div className="viewButton">Modifier</div>
            </Link>
            <div
              className="deleteButton"
              onClick={() => handleDelete(params.row.id)}
            >
              Delete
            </div>
          </div>
        );
      },
    },
  ];
  return (
    <div className="datatable">
      <div className="datatableTitle">
        Add New Article
        <Link to="/users/new" className="link">
          <AddBusinessIcon className="icon" /> Add Article
        </Link>
      </div>
      <DataGrid
        className="dataGrid"
        rows={data}
        columns={userColumns.concat(actionColumn)}
        pageSize={9}
        rowsPerPageOptions={[9]}
        checkboxSelection
      />
    </div>
  );
};

export default Datatable;

Single.jsx:

//...

const Single = ({ inputs, title }) => {
  const [data, setData] = useState({
    code: "",
    article: "",
    price: 0,
    vat: 0,
    status: 0,
    company_id: 0,
  });

  const normalize = (v) => ({
    code: v.code,
    article: v.article,
    price: Number(v.price),
    vat: Number(v.vat),
    status: Number(v.status),
    company_id: Number(v.company_id),
  });

  function handle(e) {
    const newdata = { ...data };
    newdata[e.target.id] = e.target.value;
    setData(newdata);
    console.log(newdata);
  }

  const handleClick = async (e) => {
    e.preventDefault();
    const body = normalize(data);

    await fetch("https://api.factarni.tn/article/create", {
      method: "PUT",
      body: JSON.stringify(body),
      headers: {
        "Content-Type": "application/json",
        Authorization:
          "Bearer eyJhbGciOiJ...w2QWltkyA",
      },
    });
  };

  return (
    <div className="New">
      <Sidebar />
      <div className="newContainer">
        <Navbar />
        <div className="top">
          <h1>{title}</h1>
        </div>
        <div className="bottom">
          <div className="right">
            <form>
              <div className="formInput"></div>
              {inputs.map((input) => (
                <div className="formInput" key={input.id}>
                  <label>{input.label} </label>
                  <input
                    type={input.type}
                    placeholder={input.placeholder}
                    onChange={(e) => handle(e)}
                    id={input.label}
                    name={input.label}
                    value={input.label}
                  />
                </div>
              ))}
              <button onClick={handleClick}>Update</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Single;

推荐答案

在Database.jsx中:

// ... code
<Link to={{ pathname: "/users/test", state: { id: params.row.id }}} style={{ textDecoration: "none" }}>
    <div className="viewButton">Modifier</div>
</Link>
// ... code

在Single.jsx中:

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

// ... later in render function
const { state } = useLocation() // state.id should have your id

Reactjs相关问答推荐

如何在useEffect中使用useParams()

react 路由导航不工作,但手动路由工作

使用Thattle和Use Effect setTimeout进行搜索有什么不同

在Reaction常量函数中未更新状态变量

当useEffect和onClick处理程序都调用useCallback函数时,有没有办法对useEffect产生额外的影响?

这两个子元素在Reaction Native中使用的有什么不同?

无法在REACTION TANSTACK查询中传递参数

尽管所有页面在 Reactjs 中都是公开的,但始终导航到特定页面

react 本机屏幕转换

列表中的每个子项都应该有一个唯一的keyprops .在react 应用程序中

为 Next.js 应用程序目录中的所有页面添加逻辑的全局文件是什么?

对于 ref 上的可见 prop 或 open 方法来react 组件,哪种方式更好?

使用jest如何覆盖对象的模拟?我正在使用`jest.mock()`来模拟对象,并希望 for each 测试用例覆盖模拟.

当我在 React Router Dom 中使用两个参数并直接在页面上导航时,数据获取没有发生

如何在屏幕上使用相同的可重用

使用 MuiCssBaseline 在所有 MUI v5 标签上设置边距 0

如何在悬停时更改 MUI 卡内容

我应该使用 useEffect 来为 React Native Reanimated 的 prop 值变化设置动画吗?

使用 React、Redux 和 Firebase 的无限循环

单击三个按钮之一后如何显示特定按钮的内容?单击其中一个按钮后应隐藏所有按钮