typescript - react-redux 无法访问组件道具
问题描述
上下文:简单的 React Native 应用程序利用 Redux 来管理复杂性。
版本:
- 打字稿 v3.0.3
- 反应原生 v0.56.0
- 还原 v4.0.0
- @types/react-redux v6.0.9
- @types/redux v3.6.0
问题:我的 JSX 主组件看不到属性(注释中包含错误)。
第一个文件:
//app.tsx
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<MainRedux ownProp="as"/> //[1]: Type '{ ownProp: string; }' is not assignable to type 'Readonly<AllProps>'. Property 'appPermissions' is missing in type '{ ownProp: string; }'.
</Provider>
);
}
}
和第二个文件:
//MainRedux.tsx
export interface ApplicationState { //originally in another file
appPermissions: AppPermissionsState;
//...
}
type StateProps = ApplicationState; //alias appPermissions is in the Application State
interface DispatchProps {
getPermissions: typeof getPermissions;
//...
}
interface OwnProps {
ownProp: string;
}
type AllProps = StateProps & DispatchProps & OwnProps;
export class MainRedux extends React.Component<AllProps> {
constructor(props: AllProps) {
super(props);
props.getPermissions(); //[2]: TypeError: undefined is not a function (evaluating 'props.getPermissions()')
}
//...
} //class
//...
const mapStateToProps: MapStateToProps<
StateProps,
OwnProps,
ApplicationState
> = (state: ApplicationState, ownProps: OwnProps): StateProps => {
return state;
};
const mapDispatchToProps: MapDispatchToPropsFunction<
DispatchProps,
OwnProps
> = (dispatch: Dispatch<AnyAction>, ownProps: OwnProps): DispatchProps => ({
getPermissions: bindActionCreators(getPermissions, dispatch)
//...
});
export default connect<StateProps, DispatchProps, OwnProps, ApplicationState>(
mapStateToProps,
mapDispatchToProps
)(MainRedux);
而,[1] 是编译时错误,[2] 是运行时错误。
谁能告诉我怎么了?先感谢您。
编辑:我将一些调试信息放入mapStateToProps
and mapDispatchToProps
,但似乎connect
没有调用它们。我可以更进一步,假设 evenconnect
没有被调用。
解决方案
看起来像是状态到道具的映射
作为测试,您可以将其放入 MapStateToProps 函数中:
const mapStateToProps: MapStateToProps<StateProps,OwnProps,ApplicationState> =
(state: ApplicationState, ownProps: OwnProps): StateProps => {
return {test : "hello"}
};
看看你是否test
在console.log(this.props)
你的componentDidMount()
如果是这样,您需要映射您的对象:
return {
propkey1 : state.propkey1,
propkey2 : state.propkey2
.... etc
}
但是,如果没有代码库,很难确定。
推荐阅读
- python - 无法使用 anaconda 安装 Python 3.x
- python-3.x - 获取 kerberos 令牌的延迟:python gssapi securitycontext
- python - 具有递归或时间戳错误的最佳假期搜索
- c# - ManualResetEventSlim.Wait() - TimeSpan 与 int 中的超时
- javascript - 在 JS 中使用 IIFE 通过创建私有变量来保护数据
- automata - 图灵机计算器
- javascript - 对象内对象的交叉比较
- git - 使用无法从开发工作站访问的 Git 存储库
- spring - Spring actuator 健康检查 - 如何确保与数据库存在活动连接
- javascript - Velocity.js 脚本在 Safari 浏览器中不起作用