我有一个医生列表,我正在尝试在选择时动态呈现详细信息页面。我看到大多数人建议通过 Route 组件传递 props,如下所示:
<Route path={`${match.url}/:name`}
component={ (props) => <DoctorView doctor={this.props.doctors} {...props} />}
/>
虽然我不清楚应该在哪里执行此操作。我在 DoctorList 和 DoctorItem 中尝试过,但没有成功。因此,我在 App 组件中设置了 Route,并且可以选择一名医生,然后它会渲染 DoctorView 组件并显示 match.params 属性。但是如何将选定的医生数据获取到DoctorView呢?我可能让这件事变得比应有的更加困难。这是我的代码:
App.jsx
const App = () => {
return (
<div>
<NavigationBar />
<FlashMessagesList />
<Switch>
<Route exact path="/" component={Greeting} />
<Route path="/signup" component={SignupPage} />
<Route path="/login" component={LoginPage} />
<Route path="/content" component={requireAuth(ShareContentPage)} />
<Route path="/doctors" component={requireAuth(Doctors)} />
<Route path="/doctor/:name" component={requireAuth(DoctorView)} />
</Switch>
</div>
);
}
DoctorList.jsx
class DoctorList extends React.Component {
render() {
const { doctors } = this.props;
const linkList = doctors.map((doctor, index) => {
return (
<DoctorItem doctor={doctor} key={index} />
);
});
return (
<div>
<h3>Doctor List</h3>
<ul>{linkList}</ul>
</div>
);
}
}
DoctorItem.jsx
const DoctorItem = ({ doctor, match }) => (
<div>
<Link
to={{ pathname:`/doctor/${doctor.profile.first_name}-${doctor.profile.last_name}` }}>
{doctor.profile.first_name} {doctor.profile.last_name}
</Link>
</div>
);
DoctorView.jsx
const DoctorItem = ({ doctor, match }) => (
<div>
<Link
to={{ pathname:`/doctor/${doctor.profile.first_name}-${doctor.profile.last_name}` }}>
{doctor.profile.first_name} {doctor.profile.last_name}
</Link>
</div>
);
我可以通过 Redux 访问医生列表,我可以连接组件、引入列表并比较 id,但这感觉像是很多不必要的步骤。
最佳答案
But how do I get the selected doctor data to DoctorView?
请记住,使用 /items
和 /items/:id
这样的路径会创建一个场景,您可能会首先登陆详细信息页面。
你:
a) 无论如何都要获取所有项目,因为您可能会返回列表页面?
b) 只获取该一项的信息?
这两个答案都不是“正确的”,但最终您会得到三个可能的信息:
1) 项目 ID
2)单个项目
3) 项目列表(可能包含也可能不包含详细信息页面所需的所有信息)
无论您想在哪里显示项目的完整详细信息,都需要通过 props 访问该项目。将所有项目详细信息放入 url 中会很困难,而且不可能实现情况 A。
由于您使用的是 redux,因此从 url 中的标识符中获取项目的详细信息是非常有意义的
export default
connect((state, props) => ({
doctor: state.doctorList.find(doctor =>
doctor.id === props.match.params.id
)
}))(DoctorView)
^ 看起来是不是太多额外的步骤?
关于reactjs - React Router 4 将 props 传递给动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48654351/