我正在导出一个带有函数的组件,但是当我尝试在另一个组件中使用它的函数时,它会抛出一个未定义的。我已正确导入它但似乎无法使用这些功能。
import React from 'react';
export default class TeamStore extends React.Component {
_state: {
team: "None",
loaded: false
}
getState() {
return this._state.team;
}
addTeam(team) {
this._state.team = team;
this.onChange();
}
onChange() {}
}
import React from 'react';
import Jumbotron from 'react-bootstrap/lib/Jumbotron';
import TeamStores from './TeamStore';
export default class JumbotronNews extends React.Component {
getStateFromStore() {
return TeamStores.getState(); //this is the one throwing the error
}
constructor() {
super();
this.state = this.getStateFromStore();
}
componentDidMount() {
TeamStore.onChange = this.onChange;
}
onChange() {
this.setState(this.getStateFromStore());
}
render() {
return (
<Jumbotron>
<h1 style={{"marginLeft": "270px"}}>{this.state.team}</h1>
</Jumbotron>
)
}
}
答案 0 :(得分:0)
我看到了一些问题。
您将TeamStore
定义为一个类,但您正在使用它,就像在其上定义了函数的常规对象一样。如果你想把它作为一个类,你必须在调用函数之前先将它实例化。
您已将TeamStore
类定义为React.Component
的扩展名,但您并未将其用作React组件。
在JumbotronNews
文件中,您将TeamStore
导入为TeamStores
,但您将componentDidMount
用作TeamStore
。
答案 1 :(得分:0)
您想要的是 Mixin ,这是一个例子:
var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.map(clearInterval);
}
};
var TickTock = React.createClass({
mixins: [SetIntervalMixin], // Use the mixin
getInitialState: function() {
return {seconds: 0};
},
componentDidMount: function() {
this.setInterval(this.tick, 1000); // Call a method on the mixin
},
tick: function() {
this.setState({seconds: this.state.seconds + 1});
},
render: function() {
return (
<p>
React has been running for {this.state.seconds} seconds.
</p>
);
}
});
在此页面上检查Mixin:https://facebook.github.io/react/docs/reusable-components.html
也可以使用基于ES6的不同实现:https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750