我一直在尝试在组件加载时调用一个方法,以便在初始页面加载时对数据进行排序。
在下面的示例中,我将状态设置为初始数据,然后立即调用 sort() 方法对数据进行排序。
export default class Leaderboard extends React.Component {
constructor(){
super();
this.state = {
rows:
[{name: "Jonny", points: 124, total: 1234},
{name: "Bob", points: 321, total: 4321},
{name: "Sally", points: 234, total: 31234},
{name: "Katie", points: 613, total: 12333},
{name: "Cameron", points: 1232, total: 5231}]
};
this.sort("daily");
}
sort(args){
if (args === "daily") {
var sorted = this.state.rows.sort(function(a, b){
return a.points-b.points;
});
this.setState(sorted.reverse());
}
if (args === "total") {
var sorted = this.state.rows.sort(function(a, b){
return a.total-b.total;
});
this.setState(sorted.reverse());
}
}
render() {
const Rows = this.state.rows.map((obj, i) => <Row key={i} num={i} name={obj.name} points={obj.points} total={obj.total}/> );
return (
<div className="col-md-10 col-md-offset-1">
<table className="table table-hover">
<tbody>
<tr>
<th colSpan="4" className="text-center">Leaderboard</th>
</tr>
<tr>
<th> Number </th>
<th> Name </th>
<th onClick={() => this.sort("daily")}> Points </th>
<th onClick={() => this.sort("total")}> All time points </th>
</tr>
{Rows}
</tbody>
</table>
</div>
);
}
这有效,但我在控制台中收到一条消息:
警告:setState(...):只能更新已安装或安装的组件。这通常意味着您在未安装的组件上调用了 setState() 。这是一个空操作。请检查排行榜组件的代码。
是否可以安全地忽略此警告?
最佳答案
发生这种情况是因为您在构造函数中调用了 this.sort("daily")
,它在安装组件之前调用了 this.setState
。
而是在 componentWillMount
或 componentDidMount
中调用 this.sort("daily")
。
编辑
正如@robertkelp 指出的那样,您应该将排序和 setState 更改为如下所示:
var sorted = this.state.rows.slice(0).sort(function(a, b){
return a.points-b.points;
});
this.setState({rows: sorted.reverse()});
请注意,它正在执行 slice(0)
以克隆您的数组并将状态正确设置到 rows
属性中。
关于javascript - 只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38981157/