reactjs - 设置 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>
即使将“任何”粘贴在其中似乎也不正确。
这是一个更清晰的:
它建议使道具可选:
interface NavProps{
loggedIn?: boolean,
loggingIn?: boolean
}
class Navigator extends Component<NavProps>
解决方案
推荐阅读
- c# - NET CORE 2.0 将 IHtmlLocalizer 放入 _Layout 并在 .cshtml 文件中使用
- javascript - Javascript删除事件并添加事件
- python - 检查坐标间隔中是否存在值
- python - 在python中获取给定周数的第一天和最后一天
- javascript - 将表单值传递给 react.js 中的 onclick 处理程序
- docker - 作为多阶段构建的一部分安装卷
- java - 我可以让 Selenium WebDriver 在每次操作之前等待吗?(出于调试目的)
- regex - MongoDB 正则表达式数组(反向正则表达式?)
- java - Solr 通用搜索,如何从搜索中删除某些字段?
- ios - 使用 cocoapods 将 Xcode 默认调试方案更改为不同的方案