reactjs - 未在另一个组件内的组件中调用 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 的概念。
解决方案
您可以通过替换来简单地修复您的代码
import { Sample } from './Sample';
和
import Sample from './Sample';
当您使用大括号时,您表示它是导出之一,当您不指定大括号时,它是您所指的默认导出
默认导出是在您的情况下连接到 redux 的组件
推荐阅读
- flutter - 向 TextInputField 颤振添加框阴影
- nuxt.js - Apollo 模块有时不调用请求
- windows - 如何在没有断字符的情况下输出`exec.Command`的输出数据
- oracle - 使用在 Docker 容器中运行的 ksqlDB 连接到外部 Oracle 数据库
- lambda - 有没有更好的方法来创建一个带有 lambda 的 forEach 的结果的新 ArrayList
- google-apps-script - 在复制电子表格时重命名appsscript项目
- angular - 尽管请求有效,但不显示数据
- sap - 在 SLES 12 SP4 中安装 sap hana 时如何解决问题退出信号 6
- ios - 未收到远程配置回调 - iOS
- visual-studio - 使用计算行创建 SSRS 报告