如何在react中对jsx中的元素进行排序



我有一个应用程序,用户可以CRUD线程,主要结构如下,

export default function Dashboard(){
return(
<Fragment>
<CreateBoard />
<BoardList />
</Fragment>
)
}

CCD_ 1将在CCD_ 2中被调用
董事会名单

import { getBoards, deleteBoard } from "../../actions/boards"
export class BoardList extends Component {
static propTypes = {
boards: PropTypes.array.isRequired,
getBoards: PropTypes.func.isRequired,
deleteBoard: PropTypes.func.isRequired,
}
componentDidMount() {
this.props.getBoards();
}
render(){
return (
<Fragment>
<h2>Boards</h2>
<table className="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Author</th>
<th>Title</th>
<th>Created</th>
<th>Updated</th>
<th />
</tr>
</thead>
<tbody>  
// this sort does not work
{this.props.boards.length > 0 && this.props.boards.sort((boardA, boardB) => boardA.id < boardB.id)
.map(board => (
<tr key={board.id}>
<td>{board.id}</td>
<td>{board.author}</td>
<td>{board.title}</td>
<td>{board.created}</td>
<td>{board.updated}</td>
<td>
<button 
className="btn btn-danger btn-sm"
onClick={this.props.deleteBoard.bind(this, board.id)}
>
Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</Fragment>
)
}
}
const mapStateToProps = state => ({
boards: state.boards.boards
})
export default connect(mapStateToProps, {getBoards, deleteBoard})(BoardList)

尽管我对它进行了排序,但它总是按照我的列表子代顺序进行排序(较新的帖子排名第一(。如何在不每次都渲染的情况下修复它?

返回函数中的sort可能比JSX更干净。此外,您还需要将道具克隆到一个可以排序的新数组中。

render() {
const sortedBoard = [...this.props.boards].sort((boardA, boardB) => {
return boardA.id > boardB.id;
});
const sortedRows = sortedBoard.map(board => {
return (
<tr key={board.id}>
<td>{board.id}</td>
<td>{board.author}</td>
<td>{board.title}</td>
<td>{board.created}</td>
<td>{board.updated}</td>
<td>
<button
className="btn btn-danger btn-sm"
onClick={this.props.deleteBoard.bind(this, board.id)}
>
Delete
</button>
</td>
</tr>
);
});
return (
<Fragment>
<h2>Boards</h2>
<table className="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Author</th>
<th>Title</th>
<th>Created</th>
<th>Updated</th>
<th />
</tr>
</thead>
<tbody>{this.props.boards.length && { sortedRows }}</tbody>
</table>
</Fragment>
);
}

注意sort可能有点棘手。。。

let a = [ '1', '2', '10', '3' ];
a.sort();
// [ '1', '10', '2', '3' ]
let b = [1, 2, 10, 3];
b.sort((x,y) => { return x-y });
// [ 1, 2, 3, 10 ]

最新更新