简体   繁体   English

使用 getInitialState() 时出现“仅支持使用 React.createClass 创建的类”错误

[英]"This is only supported for classes created using React.createClass" error when using getInitialState()

Trying to update my form using reactjs, ComponentDidMount working fine, but cant pass value to <input type="text" name="text" value={this.state.Bio.title}/> .尝试使用 reactjs 更新我的表单,ComponentDidMount 工作正常,但无法将值传递给<input type="text" name="text" value={this.state.Bio.title}/> How do I resolve this issue?我该如何解决这个问题?

ERROR 1:错误 1:

Warning: getInitialState was defined on BioUpdateById, a plain JavaScript class.警告:getInitialState 是在 BioUpdateById 上定义的,它是一个普通的 JavaScript 类。 This is only supported for classes created using React.createClass.这只支持使用 React.createClass 创建的类。 Did you mean to define a state property instead?你的意思是定义一个状态属性吗?

ERROR 2:错误 2:

TypeError: Cannot read property 'Bio' of null类型错误:无法读取 null 的属性“Bio”

My code below:我的代码如下:

import React, { Component } from 'react';
import { withRouter } from 'react-router';

//import Form from '../components/bioUpdateForm';
import { fetchBio, updateBio } from '../action/BioAction';

class BioUpdateById extends Component {

    getInitialState() {
        return {
            Bio: {}
        };
    }

    ComponentDidMount() {
        fetchBio(this.props.params.id)
            .then((data)=> {
                this.setState( state => {
                    state.Bio = data;
                    return state;
                })})
            .catch((err)=> {
                console.log('err', err)
            });
    }

    render() {
        return (
            <div>
            <input type="text" name="text" value={this.state.Bio.title}/>
            </div>
        );
    }
};

export default BioUpdateById;

UPDATE更新

first update added, but again error from bioUpdateForm添加了第一个更新,但bioUpdateForm再次出错

import React, { Component } from 'react';
import { withRouter } from 'react-router';

import Form from '../components/bioUpdateForm';
import { fetchBio, updateBio } from '../action/BioAction';



class BioUpdateById extends Component {

state = {
  Bio: {},
};

componentDidMount()
{
 fetchBio(this.props.params.id).then((data)=> { this.setState( state =>{ state.Bio = data; return state;})}).catch((err)=>{ console.log('err', err)});

}

handleSubmit(e) {
    alert('An essay was submitted: ' + this.state.value);
    e.preventDefault();
  }

// handleSubmit(data) 
// {
//     updatebio(this.state.bio.id, data);
// };

  render() {
        return (
            <div>
              <Form onSubmit={this.handleSubmit}
                  title = {this.state.Bio.title}
                  body  = {this.state.Bio.body}
                ></Form>            
            </div>
        );
    }
};

export default BioUpdateById;

Here is my Bioupdate form这是我的 Bioupdate 表格

import React, { Component } from 'react';




class Form extends Component {


    getInitialState() {
        return {
            title: this.props.title || '',
            body: this.props.body || ''
        }
    }


    handleTitleChange(e) {
        this.setState({
            title: e.target.value
        });
    }
    handleBodyChange(e) {
        this.setState({
            body: e.target.value
        });
    }


    handleSubmit(e) {
        e.preventDefault();
        this.props.onSubmit(this.state);
    }


    render() {
        return (
            <form name="blog_post" className="form-horizontal" onSubmit={this.handleSubmit}>
                <div id="blog_post">
                    <div className="form-group">
                        <label className="col-sm-2 control-label required" htmlFor="blog_post_title">course</label>
                        <div className="col-sm-10">
                            <input type="text"
                                   id="blog_post_title"
                                   required="required"
                                   value={this.state.Bio.title}
                                   onChange={this.handleTitleChange}
                                   className="form-control"/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label required" htmlFor="blog_post_body">Field of college</label>
                        <div className="col-sm-10">
                            <input type="text"
                                   id="blog_post_body"
                                   required="required"
                                   value={this.state.Bio.body}
                                   onChange={this.handleBodyChange}
                                   className="form-control"/>
                        </div>
                    </div>

                    <div className="form-group">
                        <div className="col-sm-2"></div>
                        <div className="col-sm-10">
                            <button type="submit"
                                    id="blog_post_submit"
                                    className="btn-default btn">
                                Submit
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        );
    }
};

export default Form;

ERROR 3 : TypeError: Cannot read property 'Bio' of null错误3:类型错误:无法读取 null 的属性“Bio”

you're missing the initialization of the state in the constructor, this is why you get the exception.您在构造函数中缺少状态的初始化,这就是您收到异常的原因。

constructor(props) {
 super(props);
 this.state = {
   Bio: {}
 };
}

then when you set the state do not mutate the previous state that you receive in the callback, but return a new object然后当您设置状态时,不要改变您在回调中收到的previous state ,而是返回一个新对象

fetchBio(this.props.params.id)
 .then(data => this.setState( prevState => { return { Bio: data }}) )
 .catch(err => console.log('err', err));

And initialize the state even in the Form component in the same way you did for the BioUpdateById component并以与BioUpdateById组件相同的方式在Form组件中初始化状态

state = {
   title: this.props.title || '',
   body: this.props.body || ''
}

Don't use getInitialState , its nowhere in the new reactjs versions.不要使用getInitialState ,它在新的 reactjs 版本中无处可去。 This is happening because when your component is rendering state.Bio is undefined.发生这种情况是因为当您的组件呈现state.Bio未定义。 Place this state in your class and remove getInitialState .将此state放在您的类中并删除getInitialState

state = {
  Bio: {},
};

getInitialState is deprecated method, if you create component as a class you can define initial state as property or in constructor getInitialState是不推荐使用的方法,如果您将组件创建为类,您可以将初始状态定义为属性或在构造函数中

you should change你应该改变

getInitialState() {
    return {
        Bio: {}
    };
}

on

state = {
    Bio: {}
}

also not ComponentDidMount but componentDidMount也不是ComponentDidMount而是componentDidMount

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM