首页 > 解决方案 > 我获取了一个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....

标签: javascriptreactjssortingfetch

解决方案


您以错误的方式设置状态。尝试setState({cat: res}, some_callback_function)


推荐阅读