首页 > 解决方案 > 未在另一个组件内的组件中调用 mapsStatetoProps

问题描述

import * as React from 'react';
import { connect } from "react-redux";
import './App.css';
import logo from './logo.svg';
import { Sample } from './Sample';

export interface IAppProps {
  sap:any
}

class App extends React.Component<IAppProps> {
  constructor(props: IAppProps) {
    super(props);
  }

  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
        {this.props.sap}
        <Sample />
      </div>
    );
  }
}

export function mapStateToProps(state: any, ownProps: any) {
  return {
    sap:"THIS FROM APP"
  }
}

export default connect(mapStateToProps)(App);


import * as React from 'react';
import { connect } from "react-redux";
import './App.css';

export interface ISampleProps {
    newData?: any
}

export class Sample extends React.Component<ISampleProps> {
    constructor(props: ISampleProps) {
        super(props);
    }

    public render(): any {
        return (
            <div className="App">
                SAMPLe.....
                {this.props.newData}
            </div>
        );
    }
}

export function mapStateToProps(state: any, ownProps: any) {
    return {
        newData: "Hello world"
    }
}

export default connect(mapStateToProps)(Sample);

在 SAMPle 之后输出缺少“Hello world”... 在此处输入图像描述 然后在 App 组件的渲染中添加了一个组件,mapStateToProps 被调用为 App 组件而不是 Sample 组件。

为什么在组件中使用 mapStateToProps 时没有被调用?

代码示例是为了理解 redux/react 的概念。

标签: reactjsreduxreact-redux

解决方案


您可以通过替换来简单地修复您的代码

import { Sample } from './Sample';

import Sample  from './Sample';

当您使用大括号时,您表示它是导出之一,当您不指定大括号时,它是您所指的默认导出

默认导出是在您的情况下连接到 redux 的组件


推荐阅读