无法渲染排序数据-ReactJSr

时间:2018-04-25 12:18:54

标签: reactjs

我目前正在进行过滤和排序。

无法呈现已排序的数据

任何人都可以建议如何解决这个问题

以下是我的以下代码。

排序功能

sortByOrder(e) {
const storeSelectedSortData = e.target.value;
if (storeSelectedSortData === 'ASC') {
  this.setState({ searchResult:
  this.state.searchResult.sort((a, b) => compareStrings(a.boardTitle, b.boardTitle)) });
}
else if (storeSelectedSortData === 'DESC') {
  this.setState({ searchResult:
    this.state.searchResult.sort((a, b) => compareStrings(b.boardTitle, a.boardTitle)) });
}

}

Renderboard功能

renderBoards = (boardsList) => {
if (boardsList.length) {
  return boardsList.map(board => (
    <li key={board.boardId}>
      <h5>{board.boardTitle}</h5>
    </li>
  ));
}
};

2 个答案:

答案 0 :(得分:2)

this.state.searchResult = (this.props.storyboardList || []).filter(...

这是不正确的,您需要使用SetState更新您的状态,并且不要尝试在渲染中使用SetState

答案 1 :(得分:1)

示例代码平移您的问题Click Here

const searchBoardsData = [
  {
    boardTitle: 'Board A',
    boardId: '01',
    createdAt: '2016-10-26 13:37:00',
    modifiedAt: '2018-09-21 14:27:00',

  },
  {
    boardTitle: 'Board B',
    boardId: '05',
    createdAt: '2018-03-15 09:43:10',
    modifiedAt: '2017-02-02 02:02:02',
  },
  {
    boardTitle: 'Venn',
    boardId: '02',
    createdAt: '2018-06-16 11:46:12',
    modifiedAt: '2018-07-26 13:37:00',
  },
  {
    boardTitle: 'Board C',
    boardId: '03',
    createdAt: '2018-03-15 08:03:03',
    modifiedAt: '2018-05-17 16:24:00',
  },
  {
    boardTitle: 'Composite',
    boardId: '44',
    createdAt: '2015-06-16 11:45:32',
    modifiedAt: '2018-05-17 16:25:00',
  },
];


class Application extends React.Component {
  constructor(props) {
    super(props);
    this.state= {
    data: searchBoardsData
  }
  }
  
  compareString = (a, b) => {
    const v1 = a.toLowerCase();
    const v2 = b.toLowerCase();
    return v1 < v2 ? -1 : v1 > v2 ? 1 : 0;
  }
  
  sortData = () => {
    const sortedData = this.state.data.sort((x,y) => this.compareString(x.boardTitle,y.boardTitle));
    this.setState({
      data: sortedData
    })
  }
  
  render() {
    const headerTitle = Object.keys(searchBoardsData[0])
    return <div>
      <button onClick={this.sortData}>sort</button>
      <table>
        <tbody>
          <tr>
          {headerTitle.map((hCell, i) => {
            return <th key={i}>{hCell}</th>
          })}
          </tr>
          {
            this.state.data.map((row, i) => {
            return <tr key={i}>
              {
            Object.values(row).map((col, k) =>{
              return <td key={col}>{col}</td>
            })}
             </tr>
          })
        }
        </tbody>
      </table>
    </div>;
  }
}


React.render(<Application />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

我根据您的数据添加了一个简单的排序示例代码平台。

在您的情况下检查排序数据后是否排序,然后是setState排序数据 到一个状态变量重新组合成分。