gpt4 book ai didi

javascript - 尝试按列实现切换排序。如果我参数化 sortUsers 函数,我得到 "Maximum call stack size exceeded."

转载 作者:行者123 更新时间:2023-11-29 21:02:29 26 4
gpt4 key购买 nike

如果我不将任何参数传递给 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com