-

   rss_rss_hh_new

 - e-mail

 

 -

 LiveInternet.ru:
: 17.03.2011
:
:
: 51

:


[] React DataTables ,

, 10 2017 . 17:30 +

React- - Undertone. , , React, jQuery- DataTables, , . , React- .


, . -, , DataTables React, DOM. -, , , - ( ). , - . DataTables . , , . , React + DataTables.



Create-React-App (CRA) . CRA, React . , , CRA ( ) create-react-app (. CRA , ).


, jQuery Datatables dev-dependencies.


$ npm i --save-dev datatables.net jquery 

, CRA . , , react-datatables GitHub.


UI


. , . , , , . , , - , .




DataTables


, CRA. , Table . jQuery, DataTables , DataTables jQuerey. :


const $ = require('jquery');
$.DataTable = require('datatables.net');

, -, :


const columns = [
  {
    title: 'Name',
    width: 120,
    data: 'name'
  },
  {
    title: 'Nickname',
    width: 180,
    data: 'nickname'
  },
];

, :


class Table extends Component {
  componentDidMount() {
    $(this.refs.main).DataTable({
      dom: '<"data-table-wrapper"t>',
      data: this.props.names,
      columns,
      ordering: false,
    })
  }

  componentWillUnmount() {
    $('.data-table-wrapper')
      .find('table')
      .DataTable()
      .destroy(true)
  }

  shouldComponentUpdate(nextProps) {
    if (nextProps.names.length !== this.props.names.length) {
      reloadTableData(nextProps.names)
    } else {
      updateTable(nextProps.names)
    }
    return false
  }

  render() {
    return (
      
) } }

. render HTML- . DataTables, DOM . React , DOM. , React , false shouldComponentUpdate. , , DOM DataTables. , , . componentWillUnmount API DataTables.


Table props.names, . .



-. -, -. -, - . , Table. ( , . GitHub.) .


1) -, :


function reloadTableData(names) {
  const table = $('.data-table-wrapper').find('table').DataTable()
  table.clear()
  table.rows.add(names)
  table.draw()
}

jQuery, , , componentDidMount (data-table-wrapper). ( - , ).


2) , , ( ):


function updateTable(names) {
  const table = $('.data-table-wrapper').find('table').DataTable()
  let dataChanged = false
  table.rows().every(function() {
    const oldNameData = this.data()
    const newNameData = names.find(nameData => {
      return nameData.name === oldNameData.name
    })
    if (oldNameData.nickname !== newNameData.nickname) {
      dataChanged = true
      this.data(newNameData)
    }
    return true
  })

  if (dataChanged) {
    table.draw()
  }
}

API- draw, - .


, React. shouldComponentUpdate, .


  shouldComponentUpdate(nextProps) {
    if (nextProps.names.length !== this.props.names.length) {
      reloadTableData(nextProps.names)
    } else {
      updateTable(nextProps.names)
    }
    return false
  }

, , props.names , . , , , .



React DataTables, React DataTables DOM. , , , , .


PS


, React- ?

Original source: habrahabr.ru (comments, light).

https://habrahabr.ru/post/330656/

:  

: [1] []
 

:
: 

: ( )

:

  URL