react-router v4 - 如何使用 "component" 属性为纯函数提供参数

react-router v4 - How to provide params to a pure function using "component" attribute

我有以下代码:

const CatalogContainer = () => (
    <Match
      pattern="/catalog/:id"
      exactly
      render={({ params }) => (
        <Redirect to={`/catalog/${params.id}/titles`} />
      )}
    />
)

但是 ESLint 由于 => 抛出以下警告,这是(AFAIK)一个不好的做法,因为它在每次调用时都会创建 render 函数的新引用,而我不我不想那样。

warning JSX props should not use arrow functions react/jsx-no-bind

所以,我正在尝试使用专用但简单的组件来重构它,例如:

const DefaultRedirect = (params) => (
  <Redirect to={`/catalog/${params.id}/titles`} />
);

但是,我很难弄清楚如何使用它。

首先,我想我需要使用 component 而不是 render 属性,但我不太确定,到目前为止我还没有找到关于它的正确文档。 (编辑:https://react-router.now.sh/Match 这是 v4 的文档

我尝试了几种方法,包括以下方法,但都不起作用。

<Match
  pattern="/catalog/:id"
  exactly
  component={DefaultRedirect({ params })}
/>

我找到了一些示例,但它们都在使用 React.createClass,我宁愿不使用它,因为使用 const 似乎是新的 "best" 做事方式无状态组件。


一个可能的解决方案是使用扩展 React.Component 的 Class。但是感觉不对。 (ESLint 显示 错误

Component should be written as a pure function react/prefer-stateless-function

class DefaultRedirect extends React.Component {
  render() {
    const { params } = this.props;
    return (
      <Redirect to={`/catalog/${params.businessMid}/titles`} />
    );
  }
}

来自关于 render 方法的文档:(https://react-router.now.sh/Match)

Instead of having a component rendered for you, you can pass in a function to be called when the location matches. Your render function will be called with the same props that are passed to the component. This allows for convenient inline match rendering and wrapping.

也许方便,但不是一个好的做法。

有没有办法使用纯函数来做到这一点?

免责声明 React Router v4 仍处于 alpha 阶段,其 API 仍在不断变化。根据 v4 的发展方向,这里的任何建议都可能变得毫无意义。

<Match> 渲染的每个组件都有一些提供给它的道具。它们是 locationpatternparamsisExactpathname。仅当 pattern 匹配当前 location.pathname.

时才提供最后三个

对于将为 <Match> 渲染的组件,您可以从传递给它的道具中解构 params 道具。

const DefaultRedirect = ({ params }) => (
  <Redirect to={`/catalog/${params.id}/titles`} />
);

然后您可以将该组件传递给 <Match>

<Match
  pattern="/catalog/:id"
  exactly
  component={DefaultRedirect}
/>

看起来你很接近但不完全是。

首先,您的专用功能组件应该像这样从 props 中解析参数:

const DefaultRedirect = ({ params }) => (
  <Redirect to={`/catalog/${params.id}/titles`} />
);

* 注意函数参数中的解构。

其次,当您将组件传递给 Match 时,只需传递引用,如下所示:

<Match
  pattern="/catalog/:id"
  exactly
  component={DefaultRedirect}
/>

希望对您有所帮助!