使用React js使用datajson填充select

时间:2016-10-20 23:48:45

标签: select reactjs html-select populate

我尝试使用React js填充选择,我使用react js docs(https://facebook.github.io/react/tips/initial-ajax.html)上给出的示例,它使用jquery来管理ajax调用,我&# 39;我无法使它工作,到目前为止,我有这个:

这里是codepen:http://codepen.io/parlop/pen/jrXOWB

    //json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc  ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
  getInitialState: function() {
    return {
      opts:[]      
    };
  },

  componentDidMount: function() {
    var source="https://api.myjson.com/bins/3dbn8";
    this.serverRequest = $.get(source, function (result) {
      var arrTen = result[''];
      for (var k = 0; k < ten.length; k++) {
            arrTen.push(<option key={opts[k]} value={ten[k].companycase_id}> {ten[k].name} </option>);
        }

    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    return (
      <div>        
        <select id='select1'>
          {this.state.opts}
         </select>
      </div>
    );
  }
});

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

HTML

<div id="root"></div>

任何想法如何使其有效,谢谢。

1 个答案:

答案 0 :(得分:2)

您需要调用setState来实际更新视图。这是一个可行的版本。

//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc  ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
    return {
      opts:[]      
    };
},

componentDidMount: function() {
  var source="https://api.myjson.com/bins/3dbn8";
  this.serverRequest = $.get(source, function (result) {
    var arrTen = [];
    for (var k = 0; k < result.length; k++) {
        arrTen.push(<option key={result[k].companycase_id} value={result[k].companycase_id}> {result[k].name} </option>);
    }
    this.setState({
      opts: arrTen
    });
  }.bind(this));
},

  componentWillUnmount: function() {
  this.serverRequest.abort();
},

render: function() {
  return (
    <div>        
      <select id='select1'>
        {this.state.opts}
      </select>
    </div>
  );
 }
});

ReactDOM.render(
   <App />,
  document.getElementById('root')
);