我试图构建一个react js jquery datatables可重用组件。
问题是:
状态更改后,如何正确刷新datatables记录?
我已经尝试直接从道具将数据分配给map函数。通过这种方式,表被呈现,但它与jquery数据表分离,使其变得无用。
所以我想在组件上使用一个单独的状态,它可以使用道具从父组件接收它的值。
但它也不起作用。
我不断收到有关componentdidupdate的浏览器警报,声明如下:
“datatables警告:表id=datatables\u table\u 0-无法重新初始化datatable。有关此错误的详细信息,请参阅http://datatables.net/tn/3"
似乎不知何故,我正试图改变一些我不感兴趣的事情。
我也不知道updateplugin()上的jquery.datatables方法调用是否正确。
有人能帮忙吗?
我迷路了!
以下是迄今为止我的datatables组件:
import React, { Component } from 'react'
import Column from './dataTable.Column'
import Row from './dataTable.Row'
const $ = require('jquery')
$.DataTable = require('datatables.net')
export default class DataTable extends Component {
state = {
recordList: []
}
componentDidMount() {
this.setupPlugin()
}
componentDidUpdate(){
if(this.props.recordList.length != this.state.recordList){
this.setState({recordList: this.props.recordList})
console.log(this.props.recordList)
this.updatePlugin()
}
}
render(){
return(
<table
className="table table-bordered table-hover table-striped"
width="100%"
ref={el => this.el = el}>
<thead>
<tr>
{this.props.columnList.map(col => (
<Column
key={col.Caption}
caption={col.Caption}
alRight={col.alRight}
/>
))}
</tr>
</thead>
<tbody>
{this.state.recordList.map(record => (
<Row
keyFieldName={this.props.keyFieldName}
key={record[this.props.keyFieldName]}
columnList={this.props.columnList}
record={record}
/>
))}
</tbody>
</table>
)
}
setupPlugin() {
this.$el = $(this.el);
this.$el.DataTable({
"language": {"url": "https://cdn.datatables.net/plug-ins/1.10.25/i18n/Portuguese-Brasil.json"},
"responsive": true,
"order": [[ 1, "asc" ]],
"columnDefs": [
{
orderable: false,
className: 'reorder',
targets: 0
}
]
});
}
updatePlugin() {
$(this.el).dataTable("ajax.reload()");
}
}
这是父组件,这一个非常简单。
import React, { Component } from 'react'
import backEndAPI from '../../main/services/backEndAPI'
import BaseForm from '../../template/baseForm'
import DataTable from '../../template/dataTable/dataTable'
export default class CidadeList extends Component {
tableColumns = [
{"Caption": "Código", "FieldName": "ID", "alRight": true},
{"Caption": "Nome", "FieldName": "Nome"},
{"Caption": "Estado", "FieldName": "Estado"}
]
state = {
recordList: [],
}
async componentDidMount() {
await this.doGetRecords()
}
async doGetRecords() {
const response = await backEndAPI.get('/cidade');
this.setState({ recordList: response.data });
}
render(){
return(
<BaseForm
caption='Cidades'
>
<div className='col-sm-12'>
<div className="row">
</div>
<DataTable
tableName="CidadesList"
keyFieldName="ID"
columnList={this.tableColumns}
recordList={this.state.recordList}
/>
</div>
</BaseForm>
)
}
}
暂无答案!
目前还没有任何答案,快来回答吧!