设置PROPS类型的正确方法是什么?

时间:2020-02-18 03:21:47

标签: reactjs typescript react-redux

我正在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;

如果没有,我会收到一条错误消息,指出“ log.In”不在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 is missing the following properties from ReadOnly error in React Native with TypeScript app

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

class Navigator extends Component<any, any> 

即使在其中贴上“任何”似乎都不对。

这里是一个更清晰的地方:

TS2739 - Type missing in following properties

建议将道具设置为可选

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

class Navigator extends Component<NavProps>

2 个答案:

答案 0 :(得分:4)

我们可以在the TypeScript docs here中看到它:

class Navigator extends Component<NavProps> {

这是我的计算机上的外观:

enter image description here

答案 1 :(得分:1)

根据我上面的评论,我已经对此进行了测试,根本没有问题

interface NavProps {
  loggedIn: boolean
  loggingIn: boolean
}

class Navigator extends Component <NavProps> {
  public render() {
    const { loggedIn } = this.props
    console.log(loggedIn)
    return null
  }
}

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

export default connect(mapStateToProps, null)(Navigator)

除了您的问题中我没有RootReducer类型


更新:也尝试这样写connect

export default connect<NavProps>(mapStateToProps, null)(Navigator)