gpt4 book ai didi

reactjs - 警告 : getInitialState was defined on DimensionPicker, 一个普通的 JavaScript 类。仅支持使用 React.createClass 创建的类

转载 作者:行者123 更新时间:2023-12-03 13:43:13 25 4
gpt4 key购买 nike

我正在尝试编写我的第一个 react 控件。这是我写的

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;

非常令人惊讶的是,我收到了一个错误

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?

我发现这非常令人困惑,因为显然我的组件源自 React.Component

最佳答案

埃里克的评论是正确的。您使用的是 ES6 类,这意味着不支持 getInitialState。您需要更改此设置:

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)
};
}

关于reactjs - 警告 : getInitialState was defined on DimensionPicker, 一个普通的 JavaScript 类。仅支持使用 React.createClass 创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com