我在尝试使用es6类声明创建我的可触摸组件时遇到此错误:
Warning: getInitialState was defined on SearchResults,
a plain JavaScript class. This is only supported for
classes created using React.createClass. Did you mean
to define a state property instead?
我将在可焊接文档上发表这个例子:
http://fluxible.io/api/components.html
我是否正确地声明了我的助焊剂成分?它没有初始状态时出错,所以看起来它没有被调用。
import React from 'react';
import SearchStore from '../stores/SearchStore';
import Product from './Product';
class SearchResults extends React.Component {
static contextTypes = {
executeAction: React.PropTypes.func.isRequired,
getStore: React.PropTypes.func.isRequired
};
static propTypes = {
results: React.PropTypes.array
};
static defaultProps = {
results:[]
};
getInitialState () {
return this.getStoreState();
}
getStoreState () {
return {
results: this.context.getStore(SearchStore).getResults()
}
}
componentDidMount () {
this.context.getStore(SearchStore).addChangeListener(this._onStoreChange);
}
componentWillUnmount () {
this.context.getStore(SearchStore).removeChangeListener(this._onStoreChange);
}
_onStoreChange () {
this.setState(this.getStoreState());
}
render() {
var main;
if (this.state && this.state.results && this.state.results.length) {
let products = this.state.results.map(function (product) {
return (
<Product
key={product.id}
imageUrl={product.image_url_large}
description={product.description}
name={product.name}
maxPrice={product.price_max}
minPrice={product.price_min}
/>
);
}, this);
main = (
<section id="results">
<ul id="todo-list">
{products}
</ul>
</section>
);
}
return (
<div>
<header id="header">
<h1>Search Results</h1>
</header>
{main}
</div>
);
}
}
export default SearchResults;
答案 0 :(得分:0)
您不应该使用React Components的ES6类样式来使用getInitialState。相反,初始状态属于构造函数。
https://facebook.github.io/react/docs/reusable-components.html#es6-classes
API类似于React.createClass,但getInitialState除外。您可以在构造函数中设置自己的state属性,而不是提供单独的getInitialState方法。
您可能还想查看connectToStores
,而不是尝试按照现在的方式将其连接到商店。
http://fluxible.io/addons/connectToStores.html
答案 1 :(得分:0)
我决定如此
class Tooltip extends React.Component {
constructor (props) {
super(props);
this.state = {
handleOutsideClick: this.handleOutsideClick.bind(this)
};
}
componentDidMount () {
window.addEventListener('click', this.state.handleOutsideClick);
}
componentWillUnmount () {
window.removeEventListener('click', this.state.handleOutsideClick);
}
}