【问题标题】:Use react-redux connect in typescript在打字稿中使用 react-redux 连接
【发布时间】:2018-04-16 16:29:14
【问题描述】:

我尝试使用 redux 和 react-router-dom 在 typescript 中构建一个 react 应用程序。当我将 redux 添加到我的应用程序时,我遇到了打字问题。因此,我创建了以下最小示例,只有一页 test-page

App.jsx

import * as React from 'react';
import { Route, Redirect } from 'react-router-dom'
import Test from './containers/test-page'
import './App.css';

class App extends React.Component {
  render() {
    return (
      <div className="ui container" id="main">
        <Route exact path="/" render={() => <Redirect to="/test" />}/>
        <Route exact path="/test" component={Test} />
      </div>
    );
  }
}

export default App;

测试页面的容器如下所示。它会在调用 connect 时产生输入错误。

containers/test-page/index.tsx

import { Dispatch } from 'redux'
import { connect } from 'react-redux'
import TestPage from './test-page'

function mapDispatchToProps(dispatch: Dispatch<any>) {
  return dispatch({ type: 'ALERT_USER' });
}

function mapStateToProps(state: any) {
  return { label: 'my test label' }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TestPage)

容器使用以下反应组件,在生产中应该为路由器渲染一个页面。它产生两个错误,见下文。

containers/test-page/test-page.tsx

import * as React from 'react';

export namespace Test {
  export interface Props {
    alert: () => void;
    label: string;
  }

  export interface State {
  }
}

export default class TestPage extends React.Component {

  constructor(props?: Test.Props, state?: Test.State, context?: any) {
    super(props, context);
  }

  sendAlert = () => {
      this.props.alert()
  }

  render() {
    return (
      <div>
        <h1>Test</h1>
        <button onClick={this.sendAlert}>{this.props.label}</button>
      </div>
    );
  }
}

错误信息:

proxyConsole.js:54 ./src/containers/test-page/test-page.tsx
(20,18): error TS2339: Property 'alert' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'.

proxyConsole.js:54 ./src/containers/test-page/test-page.tsx
(27,54): error TS2339: Property 'label' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'.

proxyConsole.js:54 ./src/containers/test-page/index.tsx
(16,3): error TS2345: Argument of type 'typeof TestPage' is not assignable to parameter of type 'ComponentType<{ label: string; } & { type: string; }>'.
  Type 'typeof TestPage' is not assignable to type 'StatelessComponent<{ label: string; } & { type: string; }>'.
    Type 'typeof TestPage' provides no match for the signature '(props: { label: string; } & { type: string; } & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

我尝试遵循不同的指南并查找示例实现,但无法解决这些问题。我不明白打字稿编译器的错误信息:

  • 为什么我定义的属性在this.props 上不存在?
  • 究竟什么不能在连接中分配?

【问题讨论】:

    标签: javascript reactjs typescript redux react-redux


    【解决方案1】:

    我注意到几点:

    1) 据我在示例中看到的以及在 TypeScript 中使用 props 时,您对 React.Component 的调用需要指定 Props 作为类型参数,如下所示:

    export default class TestPage extends React.Component<Test.Props, Test.State>{
    
        constructor(props: Test.Props) {
            super(props);
        }
    
    }
    

    您可以通过传递空接口来指定您的组件不接受propsstate,即:

    export default class TestPage extends React.Component<{}, {}>{
    
        // constructor becomes 'useless' at this point and is not needed
        constructor() {
            super();
        }
    
    }
    

    我认为这解释了为什么您的调用签名不匹配以及为什么在 this.props 上没有可见的属性 - TS 看到 ReadOnly{} 的接口,因为它没有传入类型参数。

    2) 您的mapStateToProps 函数看起来不太正确。 mapStateToProps 接受两个参数,state(引用你的 Redux store)和 ownProps 作为可选的第二个参数,它引用从父级传递下来的 props。所以mapStateToProps 应该是这样的:

    function mapStateToProps(state: any, ownProps: { label: string }) {
    
        return {
            label: ownProps.label
        };
    }
    

    这是我对 connect 抛出错误的猜测 - 它只是一个你断言 Redux 应该如何处理来自 storeprops 来自父级的组合的断言的地方。让我知道这是否可行。

    【讨论】:

      【解决方案2】:

      这不起作用,因为 connect 是一个通用函数。这意味着您需要提供额外的类型参数。

      connect<StateProps, DispatchProps>({
          mapStateToProps,
          mapDispatchToProps,
      })(SomeComponent);
      

      你可以找到打字实现here。你需要知道的一切都在那里 C:

      【讨论】:

        【解决方案3】:

        Type Script 应用程序的工作语法变体是:

            import * as React from 'react';
            import { connect } from 'react-redux';
        
            interface ComponentProps {
            // Your properties here
            }
        
            interface ComponentState {
            // Your properties here
            }
        
            interface MapStateToPropsTypes {
            // Your properties here
            }
        
            interface MapDispatchToPropsTypes {
            // Your properties here
            }
        
            class MyComponentName extends React.Component<ComponentProps, ComponentState> {
                constructor(props: ComponentProps) {
                    super(props);
                }
            }
        
            export default connect<MapStateToPropsTypes, MapDispatchToPropsTypes>(
              mapStateToProps,
              mapDispatchToProps)
            (MyComponentName)
        

        【讨论】:

          猜你喜欢
          • 2018-10-04
          • 2016-11-09
          • 2019-04-23
          • 2020-06-30
          • 1970-01-01
          • 2018-06-27
          • 2020-02-22
          • 1970-01-01
          相关资源
          最近更新 更多