gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:44:36 25 4
gpt4 key购买 nike

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

我做得是否正确,或者我是否错过了一个步骤,可以使 Prop 正确反射(reflect)在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

它建议将 props 设置为可选:

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

class Navigator extends Component<NavProps>

最佳答案

我们可以在 the TypeScript docs here 中看到这一点:

class Navigator extends Component<NavProps> {

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

enter image description here

关于reactjs - 设置 PROPS 类型的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60273300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com