2015-11-03 1 views
1

Я получаю эту ошибку, пытаясь создать свой плавкий компонент с классом ES6 декларацией:Ошибка пытается объявить мой плавкий компонент react.js в 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

Am Я объявляя мой плавкий компонент правильно? Это ошибки без начального состояния, поэтому похоже, что он не вызывается.

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

Вы не должны использовать getInitialState, используя стиль класса ES6 для React Components. Вместо этого исходное состояние принадлежит конструктору.

https://facebook.github.io/react/docs/reusable-components.html#es6-classes

Этот API похож на React.createClass за исключением getInitialState. Вместо предоставления отдельного метода getInitialState вы настраиваете свое собственное свойство состояния в конструкторе.

Вы также можете проверить connectToStores, а не пытаться подключить его к магазину так, как вы сейчас. http://fluxible.io/addons/connectToStores.html

+0

Вот что я думал, но пример на «Доступ Stores» здесь http://fluxible.io/api/components.html реализует функцию getInitialState() даже хотя он расширяет класс. Это ошибка в их документах? – MonkeyBonkey

+0

также - если я хочу использовать шаблон декоратора, нужно ли мне импортировать или настроить что-то в среде? Я получаю синтаксическую ошибку, используя @ decorator – MonkeyBonkey

+0

Если вы хотите использовать декоратор, вам нужно будет иметь babel в кадре-1 '{ " presets ": [" stage-1 "] }' в вашем babelrc –

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); 
    } 
} 
Смежные вопросы