我正在 build 一个小型react-router
练习项目,我试图将一些关于狗的虚构信息传递给 <Route exact path="/dogs/:name" element={in here}/>
通过传递一个返回动态 <DogDetail {...props} dog={currentDog}/>
的函数具有作为 props 传入的相关信息的组件。但是,每次我尝试这样做时,我都会收到两个错误之一:
- 位置“/dogs/hazel”处的匹配叶路由没有元素。这意味着它将呈现
<Outlet />
默认情况下使用 null 值会导致“空”页面。 - 警告:函数作为 React 子项无效。如果您返回组件而不是
<Component />
,则可能会发生这种情况从渲染。或者也许您打算调用此函数而不是返回它。
这是我的代码:
class App extends Component {
static defaultProps = {
dogs: [
{
name: "Daisy",
age: 2,
src: daisy,
facts: [
"Daisy is our newest love.",
"Daisy is a terrible guard dog.",
"Daisy wants to cuddle with you!",
"Daisy just wanted a home and now she has that plus love",
],
},
{
name: "Hazel",
age: 6,
src: hazel,
facts: [
"Hazel had soooo much energy!",
"Hazel wanted love and her big sis, Maci.",
"Hazel loved us more than anything but she would have still gone home with a stranger any day",
"Hazel loved eating food slightly more than Maci did",
],
},
{
name: "Tubby",
age: 7,
src: tubby,
facts: [
"Tubby was the smartest dog",
"Tubby did not like walks or exercise.",
"Tubby preferred to watch over the situations",
"Tubby loved eating food.",
],
},
],
};
render() {
const getDog = props => {
let name = props.match.params.name
let currentDog = this.props.dogs.find(
dog => dog.name.toLowerCase() === name.toLowerCase()
)
return <DogDetails {...props} dog={currentDog} />
}
return (
<div className="App">
<Navbar />
<Routes>
<Route exact path="/dogs" element={<DogList dogs={this.props.dogs} />}></Route>
<Route exact path="/dogs/:name" element={getDog}></Route>
<Route path="*" element={<h1>Not Found</h1>}></Route>
</Routes>
</div>
);
}
}
export default App;
现在<DogDetail />
组件仅呈现 this.props.dog.name
但当导航到任何狗的名字时我什么也没看到。
我尝试将它作为内联函数、作为绑定(bind)在构造函数中的函数以及作为 <DogDetail />
传递。组件的 prop 设置为 getDog
功能但似乎没有任何作用。我对 react-router
还很陌生但我似乎找不到有关这个特定问题的任何信息。我刚刚关注了一个代码项目视频,但显然它已经过时了。它一直在教授旧版本的react-router
我一直在尝试按照 v6 文档更新它,但这就是我陷入困境的地方。
最佳答案
在 react-router-dom@6
中,Route
组件的 element
属性仅 一个 React.ReactNode
,又名 JSX。将 getDog 函数抽象为实际的 React 组件。 Route
组件也不再具有路由属性,它们不存在。要访问路由参数,您需要使用 useParams
Hook 。
示例:
import { useParams } from 'react-router-dom';
const DogDetailsWrapper = ({ dogs = [] }) => {
const { name } = useParams();
const currentDog = dogs.find(
dog => dog.name.toLowerCase() === name.toLowerCase()
);
return <DogDetails dogs={dogs} dog={currentDog} />;
}
import { Routes, Route } from 'react-router-dom';
class App extends Component {
...
render() {
const { dogs } = this.props;
return (
<div className="App">
<Navbar />
<Routes>
<Route path="/dogs" element={<DogList dogs={dogs} />} />
<Route
path="/dogs/:name"
element={<DogDetailsWrapper dogs={dogs} />}
/>
<Route path="*" element={<h1>Not Found</h1>} />
</Routes>
</div>
);
}
}
export default App;
关于javascript - 使用react-router,我尝试传递一个返回元素到 <Route/> 元素选项的函数,但我不断收到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74535713/