【问题标题】:Typescript - Rendering Connected ComponentsTypescript - 渲染连接的组件
【发布时间】:2020-04-24 18:13:35
【问题描述】:

使用 TypeScript 和 React/Redux,我输入了一个 ConnectedComponent。但是当我尝试渲染该组件时,TypeScript 会抛出一个错误,指出未通过所需的道具。

例如。

interface Props extends MapStateProps {

}

class App extends React.Component<Props, {}> {
  render(): JSX.Element {
    return (
      <>
        <Router>
          <Switch>
            <Route path="/" component={Dashboard} />
          </Switch>
        </Router>
      </>
    );
  }
}

interface MapStateProps {
  user: UserState;
}

const MapStateToProps = (state: AppState): MapStateProps => ({
  user: state.user,
});

const connectedApp = connect(MapStateToProps, null)(App);

export {
  connectedApp as App,
};

然后当我像这样渲染组件时:

<App />

它说 App 需要 'user' 属性。如果不将用户属性设置为可选,我该如何做到这一点?

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    请试试这个,看看它是否有帮助。

    interface UserState{}
    interface AppState{
      user: UserState;
    }
    interface MapStateProps {
      user: UserState;
    }
    interface Props extends MapStateProps {}
    
    class App2 extends React.Component<Props, {}> {
      render(): JSX.Element {
        return (
          <div>
              App2
          </div>
        );
      }
    }
    
    const MapStateToProps = (state: AppState): MapStateProps => ({
      user: state.user,
    });
    
    export default connect(MapStateToProps, null)(App2);

    【讨论】:

    • 我也试过了,但永远无法让它发挥作用。它总是说 mapStateToProps 不满足 StateProps。
    • @hairyhendrix 我已经修改了代码,这对我有用。您的 MapStateProps 界面和 AppState 界面用户类型似乎都不同。
    【解决方案2】:

    更换

    export {
      connectedApp as App,
    };
    

    使用默认导出:

    export default connectedApp;
    

    然后是导入

    import {App} from './App';
    

    对于

    import App from './App';
    

    【讨论】:

    • 我以前试过,现在又试了一次,不幸的是效果一样。
    【解决方案3】:

    这对我有用:

    //...
    
    const connectedApp = connect(MapStateToProps, null)(App);
    
    export default connectedApp ;
    export { connectedApp as App};
    

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 2020-01-19
      • 2020-09-18
      • 2021-07-22
      • 2022-01-26
      • 2022-07-04
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多