【问题标题】:mapsStatetoProps not called in Component inside another componentmapstatetoProps 未在另一个组件内的组件中调用
【发布时间】:2018-07-04 14:30:59
【问题描述】:
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的概念。

【问题讨论】:

  • 您对 Sample 类的导出不正确。导入周围的括号不是示例组件的默认导出,因此this.props.newData 为空。在您的课程之前删除关键字export,并删除导入中的括号。

标签: reactjs redux react-redux


【解决方案1】:

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

import { Sample } from './Sample';

import Sample  from './Sample';

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

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

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2019-02-20
    • 1970-01-01
    • 2021-05-17
    • 2019-02-24
    • 1970-01-01
    相关资源
    最近更新 更多