【发布时间】: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