我正在react-router-dom@6.8
上工作,使用useEffect
钩子提取数据,使用useState
钩子更新数据。我的路线在Main
组件中,包含电影细节的"/films"
嵌套路线在Films
组件中。我已附上截图,其中我只能访问电影的特定ID,但不能显示电影细节。使用方法findFilms
通过Films
中的属性访问Film
。
Main.js
import { Routes, Route } from 'react-router-dom'
import { Films } from '../Films/Films'
import { Home } from '../Home/Home'
export const Main = (props) => {
return (
<div className='mainContent'>
<Routes>
<Route path="/films/*" element={<Films />}></Route>
<Route path="/planets/*" element={<Planets />}></Route>
<Route path="/people" element={<People list={people} />}>
<Route path=":id" element={<Person list={people} />}></Route>
{/* Person is passed prop with fetch results */}
</Route>
<Route path="*" element={<Home />}></Route>
</Routes>
</div>
)
}
Films.js
import React from 'react'
import { NavLink, Route, Routes } from 'react-router-dom';
import { Film } from '../Film/Film'
import './films.css'
export const Films = (props) => {
const [list, setList] = useState([]);
useEffect(() => {
(function getFilms() {
let url = 'https://swapi.dev/api/films/';
fetch(url)
.then((resp) => {
if (!resp.ok) throw new Error(resp.statusText);
return resp.json();
})
.then((data) => {
setList(data.results);
})
.catch(console.warn);
})();
}, []);
function findFilm(id) {
return list.find((item, index) => parseInt(id) === index + 1);
}
return (
<>
<div className="results">
<h2>Film List</h2>
{list.length === 0 && <p>No films...</p>}
{list.map((film, index) => (
<p key={film.title}>
<NavLink to={`/films/${index + 1}`} className={({isActive}) => (isActive ? "activeLink" : 'none')}>
{film.title}
</NavLink>
</p>
))}
</div>
<div className="details">
<Routes>
<Route path="/films/:id" element={<Film findFilm={findFilm} />} />
</Routes>
</div>
</>
)
}
Film.js
import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import React from 'react'
export const Film = ({ findFilm }) => {
const [film, setFilm] = useState(null);
const { id } = useParams();
useEffect(() => {
setFilm(findFilm(id));
}, [findFilm, id]);
let details = (
<>
<p>{film && film.title}</p>
<p>{film && film.release_date}</p>
</>
);
return (
<>
<h2>Film Details</h2>
{film && details}
</>
)
}
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './components/App/App';
import { BrowserRouter } from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
Main
组件正在App
组件中呈现。请查看代码,要么我必须使css文件className结果显示数据,要么是路由问题,代码无法在Planet是Planet子组件的页面中显示数据。
1条答案
按热度按时间gwbalxhn1#
嵌套
Routes
组件构建其相对于父Route
组件的路由。如果Films
组件呈现在path="/films/*"
上,则所有后代路由都将相对于"/films"
。后代路由path="/films/:id"
解析为"/films/films/:id"
,这可能***不是***您想要的。删除下行路由的前导
"/films"
段。