flowtype不抱怨缺少React prop

时间:2017-06-11 21:34:05

标签: javascript reactjs redux flowtype

我有以下专柜例子:

/**
 * @flow
 */

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { increment, decrement } from '../actions/counter'
import type { State } from '../store'

type Props = {
  counter: number,
  increment: Function,
  decrement: Function,
  hello: Function // There is no `hello` prop coming in to the component, but there doesn't seem to be an error
}

class Counter extends Component<*, Props, *> {
  props: Props

  render() {
    const { counter, increment, decrement } = this.props

    return (
      <div>
        <h1>{counter}</h1>
        <button onClick={decrement}>-</button>
        <button onClick={increment}>+</button>
      </div>
    )
  }
}

function mapStateToProps(state: State) {
  return {
    counter: state.counter
  }
}

function mapDispatchToProps(dispatch: Function) {
  return {
    increment: () => dispatch(increment()),
    decrement: () => dispatch(decrement())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter)

我的hello类型中有一个必需的Props道具字段,但即使该组件未收到hello道具,我似乎也没有收到任何错误。为什么会这样?

1 个答案:

答案 0 :(得分:0)

这表示缺少属性的错误。 我将<*, Props, *>更改为<void, Props, void>。 并导出没有Redux的Counter类。

 // @flow
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { increment, decrement } from '../actions/counter'
import type { State } from '../store'

type Props = {
  counter: number,
  increment: Function,
  decrement: Function,
  hello: Function // There is no `hello` prop coming in to the component, but there doesn't seem to be an error
}

// added export for Counter and void instead of *
export class Counter extends Component<void, Props, void> {
  props: Props;

  render() {
    const { counter, increment, decrement } = this.props

    return (
      <div>
        <h1>{counter}</h1>
        <button onClick={decrement}>-</button>
        <button onClick={increment}>+</button>
      </div>
    )
  }
}

function mapStateToProps(state: State) {
  return {
    counter: state.counter
  }
}

function mapDispatchToProps(dispatch: Function) {
  return {
    increment: () => dispatch(increment()),
    decrement: () => dispatch(decrement())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter)

使用计数器的类

  
// @flow
import React, { Component } from 'react';
import {Counter} from './counter';

class MainCounter extends Component
{

 render ()
 {
  return (
   <div>
    <Counter />
   </div>
  );
 }
}

enter image description here