React组件意外卸载

时间:2016-02-25 19:27:18

标签: reactjs

My React组件的行为几乎与计划相同,只是一旦我设置状态并重新渲染,它就会继续卸载并重新安装,从而导致初始状态被重置并再次经历整个生命周期。我完全不知道为什么会这样。这是我的组成部分:

var AllCompanies = React.createClass({

getInitialState: function () {
  return { companies: [] };
},

componentDidMount: function () {
  if (this.state.companies.length < 1) {
    this.fetchCompanies();
  }
},

fetchCompanies: function () {
  var that = this;
  $.ajax({
    url: 'companies',
    method: "GET",
    dataType: "json",
    success: function (user_companies) {
      that.setState({ companies: user_companies })
    }
  });
},

addCompany: function (event) {
  var that = this;
  var company = {
    name: React.findDOMNode(this.refs.companyName).value,
    ticker: React.findDOMNode(this.refs.companyTicker).value,
  }

var newCompanies = this.state.companies.concat(company)

  $.ajax({
    url: 'companies',
    method: "POST",
    dataType: "json",
    data: {company: company},
    success: function (company) {
      that.setState({ companies: newCompanies })
    }
  });
},

render: function () {

  var toRender;
  var companyForm = (
    <form className="new_company_form" onSubmit={this.addCompany}>
      <input type="text" ref="companyName" name="company[name]" placeholder="Company Name" />
      <input type="text" ref="companyTicker" name="company[ticker]" placeholder="Ticker Symbol" />
      <button>Add Company</button>
    </form>
  );

  if (this.state.companies.length > 0) {
    toRender = (<div>
                  {this.state.companies.map(function (company) {
                      return (<div key={company.id} >{company.name + ": " + company.ticker}</div>);
                    })
                  }
                </div>
                );
  } else {
    toRender = (<div>spinner.gif</div>);
  }

  return (<div>
            {companyForm}
            {toRender}
          </div>
        );
  }

}); 

0 个答案:

没有答案