我在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;
}
console.log(selectedFood);
if (this.state.foods[selectedFood]) {
var selections = this.state.selectedFoods;
var newSelections = selections.concat(selectedFood);
console.log("newSelections: "+newSelections)
var state = Object.assign(this.state, {selectedFoods: newSelections});
this.setState(state);
console.log("state: "+this.state.selectedFoods)
this.handleAffinities();
} else {
console.log("** "+selectedFood+" **");
}
},
handleAffinities: function() {
console.log("selectedFoods: "+this.state.selectedFoods.length)
if (this.state.selectedFoods.length > 0) {
var allAffinities = this.state.selectedFoods.map((food) => {
return this.state.foods[food];
});
console.log(allAffinities.length);
console.log(allAffinities);
var commonAffinities = allAffinities[0];
allAffinities.forEach((affinities) => {
commonAffinities = commonAffinities.filter((n) => {
return affinities.indexOf(n) != -1;
});
})
this.setState({affinities: commonAffinities});
} else {
this.setState({ affinities: [] });
}
},
handleRemove: function(food) {
var selectedFoods = this.state.selectedFoods;
var index = selectedFoods.indexOf(food);
var updatedSelection = selectedFoods.splice(index, 1);
this.setState({selectedFoods: selectedFoods});
this.handleAffinities();
},
为什么除了我的setState
功能之外的一切都在第一次正确执行?为什么它在第二次点击时起作用?