无法读取未定义的属性“ localeCompare”

时间:2020-10-06 14:03:10

标签: reactjs

我正在尝试对HTML表进行排序,但出现错误。我做错了什么吗? 我希望能够排序升序和降序。我正在使用 useMemo 。为此,我对名为 searchPosts 的搜索返回进行排序,并且在我的 useState 中定义了sortType和setSortType。

  import React, {useState, useEffect, useMemo} from 'react'
    import '../css/about.css'; 
    import Pagination from '../components/Pagination'
    function About() {
        const [userData, setUserData] = useState([]);
        const [loading , setLoading] = useState(false);
        const [currentPage, setCurrentPage] = useState(1);
        const [postsPerPage, setPostsPerPage] = useState(5);
        const [search, setSearch] = useState("");
        const [sortType, setSortType] = useState('asc');
        async function getData() 
            {
               let response = await fetch('https://api.github.com/users');
               let data = await response.json();
                return data;
            }
            //call getData function
            getData()
            .then(data => console.log(data)
            );//
        useEffect(() => {
            setLoading(true)
            getData()
            .then(
               data => {
                   setUserData(data) }
            )
            .catch(error => {
                console.log(error);
              })
        }, [])
    
    
          // Get current posts
          const indexOfLastPost = currentPage * postsPerPage;
          const indexOfFirstPost =  indexOfLastPost - postsPerPage;
          const currentPosts = userData.slice(indexOfFirstPost, indexOfLastPost);
    
          // changd page 
          const paginate = (pageNumber) => setCurrentPage(pageNumber);
    
          // Search Table 
          const handleFilterChange = e => {
                setSearch(e.target.value)
          }
       
    
    
       // for search 
      function DataSearch(rows) {
            const columns = rows[0] && Object.keys(rows[0]);
            return rows.filter((row) =>
            columns.some((column) => row[column].toString().toLowerCase().indexOf(search.toLowerCase()) > -1)
            );
        }
         const  searchPosts = DataSearch(currentPosts);
    

// **for Sorting** 
       const sorted = useMemo(() => {
           if(!sortType) return searchPosts;
           return searchPosts.slice().sort((a, b) => a[searchPosts].localeCompare(b[searchPosts]));
       }, [searchPosts, sortType]);
      


return (
            <div className="container">
    
                     <div>
                         <div>
                             <input value={search} onChange={handleFilterChange} placeholder={"Search"} /> 
                         </div>
                        <div> {loading }</div>
                         <table>
                             <thead>
                             <tr>
                                 <th>id</th>
                                 <th>avatar_url</th>
                                 <th>events_url</th>
                                 <th>followers_url</th>
                                 <th>following_url</th>
                                 <th>gists_url</th>
                                 <th>gravatar_id</th>
                                 <th>html_url</th>
                                 <th>
                                     login
                                     <a onClick={() => setSortType("login")}> Sort by Login</a>
                                </th>
                                 <th>node_id</th>
                                 <th>organizations_url</th>
                                 <th>received_events_url</th>
                                 <th>repos_url</th>
                                 <th>site_admin</th>
                                 <th>starred_url</th>
                                 <th>subscriptions_url</th>
                                 <th>type</th>
                                 <th>url</th>
                             </tr>
                             </thead>
                             <tbody>
                             { 
                            
                 sorted.map((item, index) => (
                             <tr  key={index}>
                                 <td>{item.id}</td>
                                <td>{item.avatar_url}</td>
                                 <td>{item.events_url}</td>
                                 <td>{item.followers_url}</td>
                                 <td>{item.following_url}</td>
                                 <td>{item.gists_url}</td>
                                 <td>{item.gravatar_id}</td>
                                <td>{item.html_url}</td>
                                 <td>{item.login}</td>
                                 <td>{item.node_id}</td>
                                 <td>{item.organizations_url}</td>
                                 <td>{item.received_events_url}</td>
                                 <td>{item.repos_url}</td>
                                 <td>{item.site_admin}</td>
                                 <td>{item.starred_url}</td>
                                 <td>{item.subscriptions_url}</td>
                                 <td>{item.type}</td>
                                 <td>{item.url}</td>
                             </tr>
                              ))
                            }
                             </tbody>
                         </table>
                         <Pagination postsPerPage={postsPerPage} totalPosts={userData.length} paginate={paginate} />
                     </div>
                
                     
            </div>
        )
    }
    
    export default About

我从stackoverflow中看到了排序示例,并复制了该示例以使用已有的代码。

1 个答案:

答案 0 :(得分:1)

首先找到这行

const [sortType, setSortType] = useState('asc');

将其更改为

const [sortType, setSortType] = useState(null);

现在转到,替换为下面的代码

const sorted = useMemo(() => {
       if(!sortType) return searchPosts;
       return searchPosts.slice().sort((a, b) => a[sortType].localeCompare(b[sortType]));
   }, [searchPosts, sortType]);

您犯的错误是 searchPosts ,而不是 sortType

然后在您的桌子上,走

<th>
     login
     <a onClick={() => setSortType("login")}> Sort by Login</a>
</th>

您应该没有任何错误。