首页 > 解决方案 > react-redux 无法访问组件道具

问题描述

上下文:简单的 React Native 应用程序利用 Redux 来管理复杂性。

版本

问题:我的 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] 是运行时错误。

谁能告诉我怎么了?先感谢您。

编辑:我将一些调试信息放入mapStateToPropsand mapDispatchToProps,但似乎connect没有调用它们。我可以更进一步,假设 evenconnect没有被调用。

标签: typescriptreact-nativereact-redux

解决方案


看起来像是状态到道具的映射

作为测试,您可以将其放入 MapStateToProps 函数中:

const mapStateToProps: MapStateToProps<StateProps,OwnProps,ApplicationState> = 
(state: ApplicationState, ownProps: OwnProps): StateProps => {
  return {test : "hello"}
};

看看你是否testconsole.log(this.props)你的componentDidMount()

如果是这样,您需要映射您的对象:

return {
 propkey1 : state.propkey1,
 propkey2 : state.propkey2
 .... etc
}

但是,如果没有代码库,很难确定。


推荐阅读