我handleSelection点击了一个按钮时调用的方法,但是,如果在达到状态时没有设置状态,则单击按钮this.setState({selectedFoods: newSelections});.方法中的其他所有内容都正确执行(因为我的各种console.logs告诉我:)).当第二次单击该按钮时,方法中的所有内容都会再次执行并且setState工作正常.
var Flavor = React.createClass({
getInitialState: function() {
return { foods: {}, selectedFoods: [], affinities: [] };
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({foods: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidUpdate: function () {
$('#select-food').selectize({
onChange: this.handleSelection
}
);
},
handleSelection: function (e) {
if (e.target) {
var selectedFood = e.target.id;
} else {
var selectedFood = e; …Run Code Online (Sandbox Code Playgroud) 我想从一个数组中为select表单生成选项.这是在React组件的render方法中,并使用JSX进行转换.
render: function(){
return(
<div className="control-group">
<select id="select-food" placeholder="Pick a food...">
<option value="">select a food</option>
{Object.keys(this.state.foods).forEach((food) => {
return (<option value={food}>{food}</option>);
})}
</select>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我可以很好地将forEach循环内的食物输出到控制台console.log(),但HTML不会生成.我在这里错过了什么才能让它发挥作用?