2016-10-20 3 views
1

私はリアクションjsを使用してselectを生成しようとしています。私はajax呼び出しを管理するためにjqueryを使用するreact js docs(https://facebook.github.io/react/tips/initial-ajax.html)の例を使用しています。populate select from datajson React jsを使用して

ここ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

実際にビューを更新するには、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') 
); 
+0

ありがとう、それは魅力的です! – Southpaw

関連する問題