【问题标题】:Getting warning when trying to use router.history.goBack with react-router尝试将 router.history.goBack 与 react-router 一起使用时收到警告
【发布时间】:2018-03-02 04:05:30
【问题描述】:

我收到此警告:

警告: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,但我不知道如何...

【问题讨论】:

    标签: reactjs react-router


    【解决方案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

    【讨论】:

      【解决方案2】:

      路由器的contextTypes 需要定义为PropTypes.object.isRequired,首先使用从npm 安装prop-types

      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>
          )
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-03
        • 1970-01-01
        相关资源
        最近更新 更多