尝试使用router.history.goBack与react-router时获得警告

时间:2018-03-01 19:53:41

标签: reactjs react-router

我收到此警告:

警告:BackButton:上下文router的类型说明无效;类型检查器函数必须返回nullError,但返回一个布尔值。您可能忘记将参数传递给类型检查器创建器(arrayOf,instanceOf,objectOf,oneOf,oneOfType和shape都需要参数)。

这是我的代码(我想重用的BackButton组件)

import React, { Component } from "react";
import { Button } from 'antd';

class BackButton extends Component {
  static contextTypes = {
    router: () => true,
  }

  render() {
    return (
      <Button
        onClick={this.context.router.history.goBack}>
        Back
      </Button>
    )
  }
}

export default BackButton;

如果可能,我最好使用PropTypes,但我不知道如何......

2 个答案:

答案 0 :(得分:1)

您的propTypes示例:

import React, { Component } from "react";
import { Button } from 'antd';
import PropTypes from 'prop-types'; // You need to add this dependency

class BackButton extends Component {
  static contextTypes = {
    router: PropTypes.object
  }

  render() {
    return (
      <Button
        onClick={this.context.router.history.goBack}>
        Back
      </Button>
    )
  }
}

export default BackButton;

您可以在此处详细了解propTypes:https://reactjs.org/docs/typechecking-with-proptypes.html

答案 1 :(得分:1)

路由器的contextTypes需要定义为PropTypes.object.isRequired,首先使用

从npm安装prop-type
npm install -S prop-types

并将其导入为

import PropTypes from 'prop-types'

并将上下文定义为

static contextTypes = {
    router: PropTypes.object.isRequired
}

所以你的代码看起来像

import PropTypes from 'prop-types'
class BackButton extends Component {
    static contextTypes = {
        router: PropTypes.object.isRequired
    }

  render() {
    return (
      <Button
        onClick={this.context.router.history.goBack}>
        Back
      </Button>
    )
  }
}