如何在映射的路线数组上传递道具?假设您有5个以上的链接,并且您只想将每个路由作为一个路由组件内的数组中的一个对象,假设每个必需的组件都已导入,这是我的RouteList组件:
const routeList = [
{
path:"/",
render: props => (<Home {...props} users={users} deleteUser={props.deleteUser} />)
},
{
path:"/about",
component:"About"
}, etc];
class RouteList extends React.Component {
constructor(props) {
super(props);
}
render() {
const routeComponents = routelists.map(
({ path, component, render }, key) => (
<Route
exact
path={path}
component={component}
render={render}
key={key}
/>
)
);
return <div>{routeComponents}</div>;
}
}
export default RouteList;
如您所见,我将渲染作为对象属性添加到了本国路线,以便可以包含道具。现在,在我的App.js中,我像上面这样导入了RouteList:
import RouteList from "./components/routelist";
class App extends React.Component {
constructor(props) {
super(props);
UniqueId.enableUniqueIds(this);
this.state = {
users: [
{ id: this.nextUniqueId(), name: "Louise", age: 28 },
{ id: this.nextUniqueId(), name: "Karen", age: 24 },
{ id: this.nextUniqueId(), name: "Jared", age: 32 },
{ id: this.nextUniqueId(), name: "Noime", age: 28 }
]
};
this.deleteUser = this.deleteUser.bind(this);
}
deleteUser = (index, e) => {
const { users } = this.state;
const newUsers = Object.assign([], users);
newUsers.splice(index, 1);
this.setState({
users: newUsers
});
};
render() {
const { users } = this.state;
return (
<Router>
<div className="App">
<Navigation />
<main>
<Switch>
<RouteList users={users} />
</Switch>
</main>
</div>
</Router>
);
}
}
我收到一个参考错误:在RouteList组件中未定义用户。或类型错误:“无法读取未定义的属性'map'”。
这是我的Home组件:
import React from "react";
import Users from "../users";
const HomePage = props => {
return (
<div className="contentContainer">
<header className="pageHeader">
<h1>Home</h1>
</header>
<ul id="user-list">
{props.users.map((user, index) => {
return (
<Users
age={user.age}
key={user.id}
index={index}
deleteEvent={props.deleteUser}
>
{user.name}
</Users>
);
})}
</ul>
</div>
);
};
export default HomePage;
答案 0 :(得分:1)
在内部render方法中移动。
const routelists = [
{
path: "/",
render: props => (
<Home {...props} users={this.props.user} deleteUser={props.deleteUser} />
)
},
{
path: "/about",
component: About
}
];
答案 1 :(得分:0)
您正在尝试在routeList数组中使用props,但是您将无法在类声明之外访问props,这是构造函数/ super方法的作用。
您还没有在任何地方声明路由列表,因此没有要映射的内容。
尝试这样的事情:
import Home from ....
class RouteList extends React.Component {
constructor(props) {
super(props);
}
render() {
const routelists = [
{
path:"/",
render: props => (<Home {...this.props} users={this.props.users}
deleteUser={this.props.deleteUser} />)
},
{
path:"/about",
component:"About"
}, etc];
const routeComponents = routelists.map(
({ path, component, render }, key) => (
<Route
exact
path={path}
component={component}
render={render}
key={key}
/>
)
);
return <div>{routeComponents}</div>;
}
}
export default RouteList;