【问题标题】:TSlint not dealing with React Native Redux components correctlyTSlint 没有正确处理 React Native Redux 组件
【发布时间】:2019-06-26 08:21:21
【问题描述】:

假设我有这个

interface IProps {
  text: string
}

class TextComponent extends PureComponent<IProps> {
  render() {
    return (
      <Text>{this.props.text}</Text>
    )
  }
}

function mapStateToProps(state: ITextComponentReduxStore) {
  return {
    text: state.text,
  }
}

function dispatchAction(dispatch: (x: any) => any) {
  return {
  }
}

export default connect(mapStateToProps, dispatchAction)(TextComponent)

当我想使用这个组件时,我只是这样做

<TextComponent />
^^^^^^^^^^^^^^^^^     <- Webstorm underlines this 

Webstorm (TSLint) 抱怨

TS2741: Property 'text' is missing in type '{}' but required in type 'Readonly<Pick<IProps, "text">>'.

我怎样才能防止这种情况发生?

props 是 Redux store 的一部分

【问题讨论】:

    标签: react-native react-redux webstorm tslint


    【解决方案1】:

    您根据需要定义道具

    interface IProps {
      text: string
    }
    

    所以你需要使用组件

    <TextComponent text={“...”}/>
    

    或者您将其定义为可选

    interface IProps {
      text?: string
    }
    

    所以你可以把它当作

    <TextComponent/>
    

    如果你想将复杂对象作为道具传递

    interface IProps {
      data?: ProfileData[];
    }
    

    和 ProfileData 接口,

    interface ProfileData {
        name: string;
        age: number;
        photos: string[];
    }
    

    你可以使用你的组件

    <TextComponent data={[{name:”John”, age:26, photos:[“url1”,”url2”]}]}/>
    

    或者如果您不想定义特定类型,您可以将其定义为any

    interface IProps {
      data?: any;
    }
    

    但打字稿不是一个好的选择。

    【讨论】:

    • hum.. 如果我有一个复杂的对象而不是 string 作为道具怎么办?有没有办法告诉 tslint 不考虑IProps
    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 2018-01-15
    • 2021-05-20
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2017-12-20
    相关资源
    最近更新 更多