简体   繁体   English

我的isLoading标志从未在构造函数()中设置为true

[英]My isLoading flag never set true in the constructor()

I'm working whith one representational component (ProjectFormUpdate) and his container (ProjectFormUpdateContainer). 我正在使用一个代表性组件(ProjectFormUpdate)和他的容器(ProjectFormUpdateContainer)。 From the container, i send an document object Project and a flag isLoading. 从容器中,我发送一个文档对象Project和一个标志isLoading。 But in a Constructor() of ProjectFormUpdate, the flag is false... the state is never seted. 但是在ProjectFormUpdate的Constructor()中,该标志为false ...永远不会设置状态。

The representational componente 代表性的组成部分

    import React, { Component} from 'react';
import ReactDOM from 'react-dom';
import { Projects } from '/imports/api/projects.js';
import PropTypes from 'prop-types'; // ES6
import { withTracker } from 'meteor/react-meteor-data';


export default class ProjectFormUpdate extends Component {
  handleUpdate(event) {
     event.preventDefault();  
     console.log("se modificó el estadoooo") 
     this.setState({
      codigo: ReactDOM.findDOMNode(this.refs.codigoInput).value.trim(),
      nombre: ReactDOM.findDOMNode(this.refs.nombreInput).value.trim()
    });

   }

  handleSubmit(event){

     this.setState({
      codigo: ReactDOM.findDOMNode(this.refs.codigoInput).value.trim(),
      nombre: ReactDOM.findDOMNode(this.refs.nombreInput).value.trim()
    });

  }


    constructor(props) {
        super(props);        
        if (!props.isLoading){

        this.state = {      
          codigo: props.oneProject.codigo,
          nombre: props.oneProject.nombre}       
        }
        else{

          this.state = {      
          codigo: 'dd',
          nombre: 'ff'}    
        }  
      }

  render() {

    const { oneProject, isLoading } = this.props;

    if (!isLoading){
      this.setState = {      
          codigo: this.props.oneProject.codigo,
          nombre: this.props.oneProject.nombre}       




    return (
      <div className="col-xs-11">
       <div className="box box-solid">
         <form className="form" onSubmit={this.handleSubmit.bind(this)} >
         <div className="box-body">
                  <div className="row">
                          <div className="col-xs-2">
                              <input
                                className = "form-control input-sm"
                                type="text"
                                ref="codigoInput"
                                placeholder="Código del Proyecto"
                                value = {this.state.codigo}//this.state.codigo}
                                onChange = {this.handleUpdate.bind(this)}
                              />
                          </div>
                          <div className="col-xs-6">
                              <input
                                className = "form-control input-sm"
                                type="text"
                                ref="nombreInput"
                                placeholder="Título"
                                value = {this.state.nombre }
                                onChange = {this.handleUpdate.bind(this)}
                              />
                           </div>
                </div>


        </div>
        <div className="box-footer">
        <button type="submit" className="btn btn-sm btn-primary btn-flat">Guardar</button>
        </div>
        </form>
     </div>
   </div>

    );
  }
  else {return (<div></div>);}
}}

ProjectFormUpdate.propTypes = {
  // This component gets the task to display through a React prop.
  // We can use propTypes to indicate it is required
  oneProject: React.PropTypes.object,   
  isLoading: React.PropTypes.bool, 
};

The Container 容器

import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { Projects } from '/imports/api/projects.js';
import ProjectFormUpdate from './ProjectFormUpdate.jsx';

export default ProjectFormUpdateContainer = withTracker(({ key1 }) => {      
    const sub = Meteor.subscribe('projects');        
    var oneProject = Projects.findOne(key1);
    var isLoading = !sub.ready();    
    return {
        oneProject,
        isLoading,
    };      
})(ProjectFormUpdate);

So... if i can't set the state, i can't set the form's values in a controled way. 所以...如果我无法设置状态,则无法以受控方式设置表单的值。 Any suggestion? 有什么建议吗?

In order to set your components state outside of the constructor() function: you must call this.setState() . 为了在constructor()函数之外设置组件状态:您必须调用this.setState() this.setState() will set it's first argument as the new state and subsequently call your component's render function. this.setState()会将其第一个参数设置为新状态,并随后调用组件的render函数。

Your if (!isLoading) statement is very dangerous. 您的if (!isLoading)语句非常危险。 Assuming !isLoading == true : your render function will infinitely fire this.setState() , thereby locking your browser. 假设!isLoading == true :您的渲染函数将无限触发this.setState() ,从而锁定您的浏览器。

Your constructor function appears correct, as is. 您的构造函数按原样显示正确。 I would allow it to set the initial application state and handle the rest from within the render() function. 我将允许它设置初始应用程序状态,并从render()函数中处理其余部分。 Alternatively, you could set your initial state within the componentWillMount() or componentDidMount() functions found here . 或者,您可以在此处找到componentWillMount()componentDidMount()函数中设置初始状态。

Within your render() function, I would omit the if (!isLoading) part and instead try returning a loading component if (isLoading == true) . 在您的render()函数中,我将省略if (!isLoading)部分,而是尝试返回一个加载组件if (isLoading == true)

You can also apply the following logic directly to your <input/> elements to set your component's state with finesse: 您还可以将以下逻辑直接应用于<input/>元素,以巧妙地设置组件的状态:

<input value={this.state.key} onChange={(event) => this.setState({key: event.target.value})}/>

I've revised your ProjectFormUpdate component as follows: 我已经对您的ProjectFormUpdate组件进行了如下修改:

import React, { Component} from 'react';
import ReactDOM from 'react-dom';
import { Projects } from '/imports/api/projects.js';
import PropTypes from 'prop-types'; // ES6
import { withTracker } from 'meteor/react-meteor-data';

export default class ProjectFormUpdate extends Component {

handleSubmit(event){
  event.preventDefault()
  console.log()
}


constructor(props) {
  super(props);
  if (!props.isLoading) {
    this.state = {
      codigo: props.oneProject.codigo,
      nombre: props.oneProject.nombre
    }
  }
  else {
    this.state = {
      codigo: '',
      nombre: ''
    }
  }
}

render() {

  const { oneProject, isLoading } = this.props;

  if (isLoading) {
    return (
      <div>isLoading == true</div>
    )
  }

  return (
    <div className="col-xs-11">
      <div className="box box-solid">
        <form className="form" onSubmit={this.handleSubmit.bind(this)} >
          <div className="box-body">
          <div className="row">
            {/* Codigo. */}
            <div className="col-xs-2">
              <input className = "form-control input-sm" type="text" ref="codigoInput" placeholder="Código del Proyecto" value={this.state.codigo} onChange={(event) => this.setState({codigo: event.target.value})} />
            </div>

            {/* Nombre. */}
            <div className="col-xs-6">
              <input className = "form-control input-sm" type="text" ref="nombreInput" placeholder="Título" value={this.state.nombre} onChange={(event) => this.setState({nombre: event.target.value}))} />
            </div>
            </div>
          </div>
          <div className="box-footer">
            <button type="submit" className="btn btn-sm btn-primary btn-flat">Guardar</button>
          </div>
        </form>
      </div>
    </div>
  )
}

ProjectFormUpdate.propTypes = {
  oneProject: React.PropTypes.object,
  isLoading: React.PropTypes.bool,
};

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

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