gpt4 book ai didi

reactjs - 使用 React 传递动态 url

转载 作者:行者123 更新时间:2023-12-04 12:35:30 36 4
gpt4 key购买 nike

感谢大家之前在How to pass and retrieve data over the url in React帮助我的努力我不知道为什么它不起作用,但我决定简化事情,只传递一个字符串而不是一个对象,但它仍然没有被读取。它没有动态 url,它只是传递字符串 ":i"或 ":book.id"或我尝试在 Link 标记中使用的任何值。
应用程序.js

import { BrowserRouter as Router, Link, Route, Switch } from "react-router-dom";
<Router>
<div className="App">
<Header />

<Switch>
<Route path="/" component={Main} />
<Route path='/:i' component={Single} />
</Switch>
</div>
</Router>


主程序
import React, { useState } from "react";
import data from "../data/books.json";
import "./main.css";
import { BrowserRouter as Router, Link } from "react-router-dom";
import Search from "./Search";


function importAll(r) {
let images = {};
r.keys().forEach((item, index) => {
images[item.replace("./", "")] = r(item);
});
console.log(images);
return images;
}

const Main = () => {

const images = importAll(require.context("../images", false, /\.(jpe?g)$/));
console.log(images);


return (

<div id="main">

{data.map((book, i) => {
return (
<div key={i} className="squares">
<img
src={images[book.picture]}
className="covers"
alt="book cover"
/>
<h3>
//////////////////////!!!!!!!!!!!!!!!!!!! here
<Link to="/:i">{book.title}</Link>
//////////////////////!!!!!!!!!!!!!!!!!!!
</h3>
<p>
Author: <em>{book.author}</em>
</p>
<p>
Price: <strong>{book.price}$</strong>
</p>
<p>{book.inventory} left in stock</p>
</div>
);
})}
;
</div>
);
};

export default Main;

Single.js

import React, { useState } from "react";
import data from "../data/books.json";
import {
BrowserRouter as Router,
Link,
Route,
useParams,
} from "react-router-dom";

const Single = (props) => {

let id = useParams();
console.log("1", id); ////logs ':i' or whatever other value I am trying to search by


最佳答案

你不应该在 Link 中传递参数像这样。

您传递参数值,例如 id。

<Link to={`/${i}`}>

然后在途中你收到它
<Switch>
<Route path="/:id" children={<Child />} />
</Switch>

Here is doc with examples

关于reactjs - 使用 React 传递动态 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62270853/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com