我有一个名为 CamperList 的 React 组件,它呈现一个表行组件数组。两个表头标签具有 onClick 事件,这些事件应该切换 this.state.toggle 并更新表。当我单击“所有时间点”标签时,表会更新,但当我单击“过去 30 天内的点”标签时,表不会更新。这是代码:
var CamperList = React.createClass({
getInitialState: function() {
return {
recent: [],
toggle: true
};
},
componentDidMount: function() {
$.get('http://fcctop100.herokuapp.com/api/fccusers/top/recent', function(data) {
this.setState({
recent: data
});
}.bind(this));
},
recent: function() {
this.setState({toggle: true});
},
alltime: function() {
this.setState({toggle: false});
},
render: function() {
var camperNodes;
if (this.state.toggle) {
camperNodes = this.state.recent.map(function(camper, index) {
return (
<Camper index={index + 1} username={camper.username} recent={camper.recent} alltime={camper.alltime} />
);
});
} else {
var alltime = this.state.recent;
alltime = alltime.sort(function(a,b) {
return b.alltime - a.alltime;
})
camperNodes = alltime.map(function(camper, index) {
return (
<Camper index={index + 1} username={camper.username} recent={camper.recent} alltime={camper.alltime} />
);
});
}
return (
<table className="table">
<thead className="blue">
<tr>
<th>#</th>
<th>Camper Name</th>
<th onClick={this.recent}>Points in past 30 days</th>
<th onClick={this.alltime}>All time points</th>
</tr>
</thead>
<tbody>
{camperNodes}
</tbody>
</table>
);
}
});
最佳答案
您的 render
函数中包含太多业务逻辑,这使得您的代码难以推理。将该逻辑移至 recent
和 alltime
函数中,以便它们根据对象的 alltime
或 重新排序 Camper 数组最近的
属性。例如:
alltime: function() {
var sortedArr = [];
//sort the array from highest alltime to lowest
this.setState({
recent: sortedArr
})
}
这将自动调用渲染函数(它应该只是渲染 UI 元素,而不包含任何逻辑)。
关于javascript - React 组件在 onClick 事件后不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36118687/