使用getInitialState()

时间:2018-10-24 13:38:52

标签: javascript reactjs

尝试使用reactjs更新我的表单,ComponentDidMount工作正常,但无法将值传递给 <input type="text" name="text" value={this.state.Bio.title}/>。我该如何解决这个问题?

错误1:

  

警告:getInitialState是在BioUpdateById(普通的JavaScript类)上定义的。仅使用React.createClass创建的类支持此功能。您是要定义状态属性吗?

错误2:

  

TypeError:无法读取null的属性“ Bio”

我的下面的代码:

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;

更新

添加了第一个更新,但再次出现来自 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;

这是我的生物更新表格

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;

错误 3:TypeError:无法读取null的属性“ Bio”

3 个答案:

答案 0 :(得分:1)

您缺少构造函数中状态的初始化,这就是为什么您会得到异常的原因。

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

然后,当您设置状态时,不要使您在回调中收到的previous state突变,而是返回一个新对象

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

并以与Form组件相同的方式,甚至在BioUpdateById组件中初始化状态

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

答案 1 :(得分:0)

不要使用getInitialState,它在新的reactjs版本中无处不在。发生这种情况是因为在渲染组件state.Bio时未定义。将此state放在您的班级中,然后删除getInitialState

state = {
  Bio: {},
};

答案 2 :(得分:0)

getInitialState是不推荐使用的方法,如果您将组件创建为类,则可以将初始状态定义为属性或在构造函数中

您应该更改

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

state = {
    Bio: {}
}

也不是ComponentDidMount而是componentDidMount