React Router 4 将道具传递给动态组件

React Router 4 Pass props to dynamic component

我有一份医生名单,我正尝试在 selected 时动态呈现详细信息页面。我看到大多数人建议通过 Route 组件传递 props,像这样:

<Route path={`${match.url}/:name`}
  component={ (props) => <DoctorView doctor={this.props.doctors} {...props} />}
  />

虽然我不清楚我应该在哪里执行它。我在 DoctorList 和 DoctorItem 中尝试过,但没有用。所以我在 App 组件中设置了路由,我可以 select 医生,然后渲染 DoctorView 组件并显示 match.params 道具就好了。但是如何将 selected 医生数据发送到 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) 只获取那一项的信息?

两个答案都不是 "correct",但在一天结束时,您将获得三个可能的信息:

1) 商品编号

2) 单个项目

3) 项目列表(可能包含也可能不包含详细信息页面所需的所有信息)

无论你想在什么地方显示一个项目的完整细节,它都需要通过道具访问该项目。将所有项目详细信息都放在 url 中会很费力,而且不可能实现情况 A。

由于您使用的是 redux,因此从 url

中的标识符中获取项目的详细信息非常有意义
export default 
  connect((state, props) => ({
    doctor: state.doctorList.find(doctor => 
      doctor.id === props.match.params.id
    )
  }))(DoctorView)

^ 看起来是不是额外的步骤太多了?

虽然上面的答案完美地解决了这个问题,但我只想补充一点,react-router

不建议使用带有 component 的内联函数

而不是做:

<Route path={`${match.url}/:name`}
  component={ (props) => <DoctorView doctor={this.props.doctors} {...props} />}
  />

您应该像这样使用它:

 <Route path={`${match.url}/:name`}
  render={ (props) => <DoctorView doctor={this.props.doctors} {...props} />}
  />

这将防止在每次安装时创建相同的组件,而是使用相同的组件并相应地更新状态。

希望这对某人有所帮助