作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我不将任何参数传递给 sortUsers 并在数组排序中对所有“.alltime”进行硬编码,它就可以正常工作。然后一旦参数化 sortUsers 函数以便它将获得 userType 字符串参数,我得到最大调用堆栈超出错误。
下面是在没有参数的情况下工作的代码。
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import $ from 'jquery';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
toggle: false
}
this.sortUsers = this.sortUsers.bind(this)
}
componentDidMount() {
axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent')
.then(resp => this.setState({users: resp.data})
)
}
sortUsers(scoreType) {
const before = this.state.users;
const sorted = before.sort((a, b) =>
this.state.toggle ? b.alltime - a.alltime : a.alltime - b.alltime
);
this.setState({
users: sorted,
toggle: !this.state.toggle
});
}
render() {
return (
<div className="App">
<table>
<tr>
<th>#</th>
<th>User Name</th>
<th>Image</th>
<th onClick={this.sortUsers}>All Time</th>
<th>Recent</th>
</tr>
{this.state.users.map((e, i) =>
<tr>
<td>{i + 1}</td>
<td>{e.username}</td>
<td><img src={e.img} width="20px"/></td>
<td>{e.alltime}</td>
<td>{e.recent}</td>
</tr>
)}
</table>
</div>
);
}
}
export default App;
下面是我将参数传递给 sortUsers 函数时所做的更改。
sortUsers(scoreType) {
const before = this.state.users;
const sorted = before.sort((a, b) =>
this.state.toggle ? b[scoreType] - a[scoreType] : a[scoreType] - b[scoreType]
);
this.setState({
users: sorted,
toggle: !this.state.toggle
});
}
...
<th onClick={this.sortUsers("alltime")}>All Time</th>
最佳答案
这将在渲染时自动调用您的函数。这就是您得到 maximum call stack size exceeded
的原因。您的函数在 render
上被调用,这导致 rerender
再次调用您的函数。
<th onClick={this.sortUsers("alltime")}>All Time</th>
这样调用它,
<th onClick={()=>this.sortUsers("alltime")}>All Time</th>
关于javascript - 尝试按列实现切换排序。如果我参数化 sortUsers 函数,我得到 "Maximum call stack size exceeded.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45809231/
如果我不将任何参数传递给 sortUsers 并在数组排序中对所有“.alltime”进行硬编码,它就可以正常工作。然后一旦参数化 sortUsers 函数以便它将获得 userType 字符串参数,
我是一名优秀的程序员,十分优秀!