【问题标题】:Flow don't understand proptypesFlow 不理解 proptypes
【发布时间】:2018-03-27 00:36:11
【问题描述】:

看看这个类:

/* @flow */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

const mapStateToProps = (state) => ({
    email: ...
});

@connect(mapStateToProps)
class UserControlPanel extends PureComponent {
    static propTypes = {
        email: PropTypes.string
    }
    logout = (ev:any) => {
        ev.preventDefault();

        ...
    }
    render() {
        const { email } = this.props;

        return (
            <div className="ucp">
                ...
            </div>
        );
    }
}

export default UserControlPanel;

这是一个简单的 React 组件类,它接受名为 email 的单个字符串 prop。但是当我运行流程时,它给了我这个错误:

[flow] 属性 email(在 React 元素 UserControlPanel 的 props 中找不到属性另见:React 元素 UserControlPanel

我错了什么?我也试过这个:

type Props = {
    email: string;
};

@connect(mapStateToProps)
class UserControlPanel extends PureComponent {
    props:Props
    static propTypes = {
        email: PropTypes.string
    }

或者这个:

type Props = {
    email: string;
};

@connect(mapStateToProps)
class UserControlPanel extends PureComponent<Props> {
    static propTypes = {
        email: PropTypes.string
    }

两者都行不通。仅使用 Component 而不是 PureComponent 也不起作用。

如何让 flow 理解我的 prop 类型并且不再显示错误消息?

【问题讨论】:

    标签: javascript reactjs properties ecmascript-6 flowtype


    【解决方案1】:

    如果您已经使用 Flow Type 验证您的类型,则不应使用 PropTypes。

    请尝试以下方法:

    /* @flow */
    import * as React from 'react';
    import { connect } from 'react-redux';
    
    const mapStateToProps = state => ({
        email: ...
    });
    
    type Props = {
      email: string,
    };
    
    @connect(mapStateToProps)
    export default class UserControlPanel extends React.PureComponent<Props> {
        render() {
            const { email } = this.props;
    
            return (
                <div className="ucp">
                    ...
                </div>
            );
        }
    }
    

    【讨论】:

    • 这不是重点,但我刚刚更新了我的 flow-bin,现在它可以工作了。谢谢。
    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    相关资源
    最近更新 更多