React + PropTypes和ESlint错误:如何验证回调的道具

时间:2018-04-26 16:41:51

标签: javascript reactjs eslint react-proptypes

我有Route from react-router

<Route
    path="/:url*"
    exact
    strict
    render={props => <Redirect to={`${props.location.pathname}/`} />}
/>

它只是向没有一个的路由添加一个尾部斜杠。

但ESLint在props.location.pathname上发出错误信号,因为props.locationprops.location.pathname都未通过PropTypes验证。

我如何验证它们?有办法吗?

注意:我不想忽略该规则:我想明确验证道具!

1 个答案:

答案 0 :(得分:0)

Ok, so following the @Tiago Coelho's comment to my question, here is the solution:

// RedirectToTrailingSlash.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { Redirect } from 'react-router-dom';

const RedirectToTrailingSlash = props => (
  <Redirect to={`${props.location.pathname}/`} />
);

RedirectToTrailingSlash
  .propTypes = { location: PropTypes.shape({ pathname: PropTypes.string.isRequired }).isRequired };

export default RedirectToTrailingSlash;

And this is the rewrote Route:

// YourComponent.jsx
...
<Route
    path="/:url*"
    exact
    strict
    component={RedirectToTrailingSlash}
/>
...