Warning: getInitialState was defined in DimensionPicker, a simple JavaScript class. This is only supported for classes created using React.createClass.

I am trying to write my first reaction control. Here is what I wrote

import React from 'react';
import DimensionPickerAction from '../actions/DimensionPickerActions.js';
import MovieLensAppStore from '../stores/MovieLensAppStore.js';

class DimensionPicker extends React.Component {

    constructor(props) {
        super(props);
        this.state = { items: [], currentItem: '' };
    }

    getInitialState() {
        this.state = {
            items: MovieLensAppStore.getAttributes(this.props.dimension),
            currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
        };
    }

    onSelectionChange(newValue) {
        DimensionPickerAction.selectionChange(this.props.dimension, newValue);
    }

    render() {
        var optionNodes = this.state.items.map((item) => {
            if (item === this.state.currentItem) 
                return(<option value="{item}" selected>{item}</option>)             
            else
                return(<option value="{item}">{item}</option>)
        });
        return(<div><select onchange="onSelectionChange">{optionNodes}</select></div>);
    }

}

export default DimensionPicker;

It is very surprising that I get an error message

Warning: getInitialState was defined on DimensionPicker, a plain JavaScript 
class. This is only supported for classes created using React.createClass. Did 
you mean to define a state property instead?

I find this very confusing because obviously my component comes from React.Component

+4
source share
2 answers

Eric's comment is correct. You are using ES6 classes, which means that it is getInitialStatenot supported. You will need to change this:

class DimensionPicker extends React.Component {

    constructor(props) {
        super(props);
        this.state = { items: [], currentItem: '' };
    }

    getInitialState() {
        this.state = {
            items: MovieLensAppStore.getAttributes(this.props.dimension),
            currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
        };
    }

:

class DimensionPicker extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            items: MovieLensAppStore.getAttributes(props.dimension),
            currentItem : MovieLensAppStore.getCurrentAttribute(props.dimension)
        };
    }
+4
source

How about this if you want to keep the original state for future use:

class DimensionPicker extends React.Component {

  constructor(props) {
    super(props);
    this._getInitialState = this._getInitialState.bind(this)
    this.state = this._getInitialState();
  }

  _getInitialState() {
    return { items: [], currentItem: '' }
  }
+1
source

Source: https://habr.com/ru/post/1625761/


All Articles