React Navigation 'navigation' is missing i

2019-03-27 08:49发布

React Navigation's introduction page suggests the use of the following destructuring assignment:

const { navigate } = this.props.navigation;

However, when I implemented React Navigation in my App, ESLint is complaining about this line describing these both errors:

'navigation' is missing in props validation (react/prop-types)

'navigation.navigation' is missing in props validation (react/prop-types)

Even though the app seems to be working as intended, how would it be possible to remove these error lines?

4条回答
Lonely孤独者°
2楼-- · 2019-03-27 09:36

One option is to add the propTypes prop to the component.

Example

LoginScreen.propTypes = {
  navigation: PropTypes.object.isRequired,
};

Another option is to disable eslint for that page and rule. More info here

Rule Options

This rule can take one argument to ignore some specific props during validation.

...
"react/prop-types": [<enabled>, { ignore: <ignore>, customValidators: <customValidator> }]
...
查看更多
祖国的老花朵
3楼-- · 2019-03-27 09:40

In case of navigation in ES5 use something like this:

LoginScreen.propTypes = {
  navigation: PropTypes.object.isRequired,
};

in ES6 use this:

static PropTypes = {
  navigation: PropTypes.object.isRequired,
};

and

import PropTypes from 'prop-types';

查看更多
Evening l夕情丶
4楼-- · 2019-03-27 09:45

Solution today (since object Proptype isn't accepted by default anymore):

export default class LoginScreen extends Component {
  static propTypes = {
    navigation: PropTypes.shape({
      navigate: PropTypes.func.isRequired,
    }).isRequired,
  }
}
查看更多
我命由我不由天
5楼-- · 2019-03-27 09:49

React.PropTypes has moved into the prop-types package since React v15.5 (see Typechecking with PropTypes).

It should be used instead of importing from react-native (the package can be added into the project via npm install --save prop-types or yarn add prop-types).

And the example code complying with "Component should be written as a pure function" rule as follows:

// In addition to other imports:
import PropTypes from 'prop-types';

const LoginScreen = ({ navigation }) => (
  <View>
    <Button
      title="Login"
      onPress={() => navigation.navigate('MainScreen')}
    />
  </View>
);

LoginScreen.propTypes = {
  navigation: PropTypes.shape({
    navigate: PropTypes.func.isRequired,
  }).isRequired,
};
查看更多
登录 后发表回答