React:如何在Ajax中设置组件中的默认值

时间:2016-10-07 20:29:51

标签: javascript reactjs

我尝试创建用于编辑现有值的表单。问题是来自ajax请求的初始数据,因此我的组件有两次:第一次是空值,第二次是数据。 Currenly我的代码没有以表格形式提供收到的数据。如何将表单中的ajax请求中获取的数据设置为初始数据,并在此表单中进一步编辑?

我的组件负责表单输入:

export default class FormInputField extends React.Component{

constructor(props) {
    super(props);
    this.state = {
        value : constants.EMPTY_FIELD,
        errorDisplay : constants.DISPLAY_NONE,
        errorMessage : constants.MESSAGE_DEFAULT_ERROR,
    }
    this.validation = this.validation.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
}

handleChange(e){
    let valid = this.validation(e.target.value);
    if (this.props.onChange){
        this.props.onChange(e, valid)
    }
}

validation(value){
    //some validation        
    this.setState({
        value : value,
        errorDisplay : errorDisplay,
        errorMessage : errorMessage
    })
    return valid;
}

handleBlur(e) {
    this.validation(e.target.value.trim());
}

    render(){
    return(
        <div className="form-group">
            <label htmlFor = {this.props.name}>{this.props.title}</label>
            <div className="col-sm-10">

                <input name={this.props.name}
                       type="text" className="form-control"
                       id={this.props.name}
                       placeholder={this.props.placeholder}
                       value={this.state.value}
                       onChange={this.handleChange}
                       onBlur={this.handleBlur}
                />
            </div>
        </div>
    )
}
}

此组件是调用表单Parent组件,方法如下:

return(
        <div style={mainFormStyle}>
            <form onSubmit={this.handleSubmit} id="addCarWashForm">

                <FormInputField
                    title = "Name*:"
                    placeholder = "Name"
                    name = "name"
                    onChange = {this.handleNameChange}
                    required = {true}
                    maxLength = {50}
                    validation = {this.validationName}
                    errorMessage = "Error"
                    defaultValue = {this.state.name.value}
                />

和默认值来自通过这种方式设置的相同Parant状态:

 constructor(props) {
    super(props);
    this.state = {
        name        :  {value : constants.EMPTY_FIELD, isValid : false}
        isCarWashDownload : false
    };
    this.setCarWashInForm = this.setCarWashInForm.bind(this);
}

componentDidMount(){
    if (!this.state.isCarWashDownload){
        let link = "/carwash/"+this.props.carWashId;
        this.serverRequest = $.get(link, function (result) {
            this.setCarWashInForm(result);
        }.bind(this));
    }

};

setCarWashInForm(carWash){
    this.setState({
        name : {value : carWash.name, isValid:true},
        isCarWashDownload : true
    })

}

2 个答案:

答案 0 :(得分:1)

由于ajax调用是异步的,因此您有几个选项:

  1. 您有标准默认值,直到日期返回并且被覆盖时才会显示。
  2. 在最初进行ajax调用时,您实际上并未呈现表单,一旦调用完成,您将使用该数据呈现表单。
  3. 根据表单所处的位置以及您希望的用户体验,这将是考虑这两种方法的主要因素。

    你现在经历的是ajax调用熄灭,反应跳转到render函数并在ajax调用完成之前呈现表单,一旦完成组件更新其状态然后重新呈现。

答案 1 :(得分:1)

儿童组件在其道具由组件更改时会重新渲染,因此在子级和父级中渲染两次,初始数据和setState之后在ajax调用响应回调中(因为Parent中的状态属性被设置为Children的props)。您可以通过在Parent类的render方法中执行简单的if来避免呈现Children组件。

render(){

    let input=null; //or some loading component to show that something is going on

    if (this.ajaxEnded) //example variable which should be changed on true when data is loaded from ajax call
    input=<FormInputField
                title = "Name*:"
                placeholder = "Name"
                name = "name"
                onChange = {this.handleNameChange}
                required = {true}
                maxLength = {50}
                validation = {this.validationName}
                errorMessage = "Error"
                defaultValue = {this.state.name.value}
            />      

   return(

     <div style={mainFormStyle}>
        <form onSubmit={this.handleSubmit} id="addCarWashForm">
        {input}
        </form>
     </div>

  );

 }

所以我们在第一个render中没有显示或加载,在ajax调用中我们设置了一些变量,表示数据被加载为布尔值true,第二个render调用显示想要的最终子组件。