我是ReactJS的新手,我正在努力了解图书馆的基本工作流程,以及React Router,没有Redux。它有一个相对较快的学习曲线,但我面临一些问题,如果我理解它的潜在机制,我就不会这样做......
我想,我面临的问题非常普遍,所以我希望有人能帮助我。情况如下:
让我告诉你代码并逐步评论:
import React from 'react';
export default class MyComponent extends React.Component {
/* Constructor, so far so good */
constructor() {
super();
}
/* componentDidMount method: it initialises the Datatable and
retrieves the data from the remote API (through an AJAX call).
But how to compose <Link> components from here with the
retrieved information??
*/
componentDidMount() {
$('#table').DataTable({
...,
ajax: {
url: "url://toMyAPI",
},
columns: [
{
data: "id",
render: ( data, type, full, meta ) => {
...
}
}
],
....
});
}
/* render method: written in JSX. In here, I usually put the
<Link to={...}></Link> components to create my anchors within
the webapp using React-Router. But now, I have to compose those
links with the information retrieved from the componentDidMount
method, which DOES NOT lets me write JSX anymore...
That is the problem.
*/
render() {
return (
<div>
<table id="table" className="table table-striped width="100%"></table>
</div>
);
}
}
非常感谢您提前;)
答案 0 :(得分:0)
React和jQuery一起变得非常笨拙。如果我了解您要尝试做什么,我建议您在componentDidMount()中进行API调用,并在promise解决设置状态时。然后在JSX中构建表而不是使用Datatables。
这样的事情:
import React from 'react';
import { Link { from 'react-router';
export default class MyComponent extends React.Component {
/* Constructor, so far so good */
constructor() {
super();
this.state = {
dataset: []
}
}
componentDidMount() {
apiCall().then(res => {
this.setState({ dataset: res }); // or however your data is formatted
});
}
render() {
return (
<div>
<table id="table" className="table table-striped width="100%">
<tbody>
{this.state.dataset.map((row, I) => {
<tr>
<td>{row.name}</td>
<td><Link to={row.href}>{row.detail}</Link></td>
</tr>
})}
</tbody>
</table>
</div>
);
}
}
我不确定您的数据是如何形成的,但是类似的东西可能效果很好。
答案 1 :(得分:-1)
从'react'导入React; 从'./../../../从您的path / dataTables.bootstrap4.min.js'导入dt;
导出默认类MyComponent扩展了React.Component {
/* Constructor, so far so good */
constructor() {
super();
}
componentDidMount() {
let table = $('#table').DataTable({
...,
ajax: {
url: "url://toMyAPI",
dom:"B"
},
columns: [
{
data: "id",
render: ( data, type, full, meta ) => {
...
}
}
],
....
});
}
render() {
return (
<div>
<table id="table" className="table table-striped width="100%"></table>
</div>
);
}
}