首页 > 解决方案 > 设置 PROPS 类型的正确方法是什么?

问题描述

我正在 REACT 中使用 REDUX,并且正在努力让 mapStateToProps 功能正常工作。

这是我的组件:

interface NavProps{
    loggedIn: boolean,
    loggingIn: boolean
}

class Navigator extends Component {

public render(){
    const { loggedIn } = this.props as NavProps;
    return (
        ...removed irrelevant code
      );
    }
}

const mapStateToProps = (state: RootReducer): NavProps => {
    const { authentication } = state;
    const { loggedIn, loggingIn } = authentication;
    return{
        loggedIn,
        loggingIn
    };
}

export default connect(mapStateToProps, null)(Navigator);

在这里你可以看到我用过:

const { loggedIn } = this.props as NavProps;

如果没有,我会收到一个错误,即“loggedIn”不在 this.props 中。

在我查看的教程中,他们都毫无问题地使用了这样的东西:

const { loggedIn } = this.props

我做得正确还是错过了使道具正确反映mapStateToProps期间分配的内容的步骤?

更新:我已经回顾了一些关于 REDUX 的教程。我现在看到他们使用的是 JSX,而不是 TSX,所以也许我必须使用类型断言来安抚 Typescript。

更新:

有几个人建议:

class Navigator extends Component <NavProps>

但是,这会产生此错误:

Type '{}' is missing the following properties from type 'Pick<NavProps, "loggedIn" | "loggingIn">': loggedIn, loggingIn  TS2739

<Router>
22 |       <div className="App">
> 23 |         <Navigator />

不确定它是否有任何区别,但这是嵌入 NAVIGATOR 的组件:

const App = () => (
  <Provider store={store}>
    <Router>
      <div className="App">
        <Navigator />
            <Switch>
              <Route exact path="/libraries" component={Libraries} />
            </Switch>
      </div>
    </Router>
  </Provider>
);

export default App;

好的,我在这里找到了一个建议:

TS2740 Type 在 React Native with TypeScript 应用程序中缺少 ReadOnly 错误中的以下属性

从下面的评论中看起来很奇怪,答案是这样做:

class Navigator extends Component<any, any> 

即使将“任何”粘贴在其中似乎也不正确。

这是一个更清晰的:

TS2739 - 以下属性中缺少类型

它建议使道具可选:

interface NavProps{
    loggedIn?: boolean,
    loggingIn?: boolean
}

class Navigator extends Component<NavProps>

标签: reactjstypescriptreact-redux

解决方案


我们可以在这里的 TypeScript 文档中看到:

class Navigator extends Component<NavProps> {

这是它在我的机器上的样子:

在此处输入图像描述


推荐阅读