在另一个组件内的Component中未调用mapsStatetoProps

时间:2018-07-04 14:30:59

标签: reactjs redux react-redux

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” ... enter image description here 然后在App组件的呈现器中添加了一个组件,该mapStateToProps被调用给App组件,而不是Sample组件。

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

该代码示例旨在了解redux / react的概念。

1 个答案:

答案 0 :(得分:0)

您只需替换

即可修复代码
import { Sample } from './Sample';

import Sample  from './Sample';

使用花括号时,表示其是出口之一, 当您不指定花括号时,它就是您要引用的默认导出

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