javascript - 我获取了一个api数据并放入了一个状态对象,我想对获取的数组进行排序并显示它
问题描述
我已经在 url 中获取了一个 json api 数据,并放入了一个状态数组,我想按 id 对该数组进行排序并显示它并将有序列表显示到 console.log 中,但它不会显示和排序。
这是我的代码:
//the class with state
class ProductsideBar extends Component {
constructor(props){
super(props)
this.state= {
cat:[],
}
}
// 我有两个函数用于获取和排序
//fetchCategory function---------------------
fetchCategory = () => {
fetch('http://localhost/wpsedighgroup/wp-json/wp/v2/mahsoolat-sanati)
.then(res => res.json())
.then((res) => {
this.setState = {
cat:res
})
};
//sort function---------------------
sortCategory = () => {
console.log('state cat is : ' , this.state.cat)
const catSOrted = this.state.cat.sort((a, b) => b.id - a.id);
console.log('Ordered is : ' , catSOrted )
}
//lifeCycle function---------------------
componentDidMount() {
this.fetchCategory();
this.sortCategory ();
// this.fetchSubcategory();
}
//render----
render () {
return(
<Grid fluid >
<Col className='side_bar'>
<div>
{this.state.cat.map( cat => {
return (
<ul>
<Link to={`/Categories/${cat.name}`}><h1>{cat.id}</h1></Link>
</li>
</ul>
)
})}
</div>
export default Prodcuts....
解决方案
您以错误的方式设置状态。尝试setState({cat: res}, some_callback_function)
推荐阅读
- azure - 如何在没有 App 和 Cred 的情况下独立创建 sp 时获取与 AzureAD 中的服务主体关联的证书的指纹
- javascript - 我正在尝试使用 css 将每个图像缩放为相同的大小(使用反应)但存在失真
- windows - 如何修复 Windows 10 Git 中的 git-upload-pack 问题
- linear-programming - 如何将离散时间的资源调度问题化为问题?
- docusignapi - 通过 eSignature Rest API 调用时,“需要签名”的等效状态是什么?
- css - CSS 嵌套下拉菜单 - 在每个下拉项名称的末尾放置向下箭头
- tensorflow - TensorFlow 构建选项可禁用不受支持的 GPU 的半精度
- python - 如何修复导入错误:scipy 的 python 中的 DLL 加载失败?
- html - 来自社交媒体的 quelltext 字母中的所有这些符号是什么,而不是 HTML 标签?
- python - 如何在循环中调用的函数内跟踪时间和日志数据值?