【发布时间】:2017-12-14 00:31:40
【问题描述】:
我是 ReactJS 的新手,我正在尝试了解库的基本工作流程,以及 React Router,没有 Redux。它的学习曲线相对较快,但我面临着几个问题,如果我很好地理解了它的基本机制,我就不会遇到这些问题......
我认为我面临的问题很常见,所以我希望任何人都可以帮助我。情况如下:
- 我有一个非常简单的 component 类,它显示了一个数据表(使用宏伟的插件 Datatables)。
- 使用对远程 API 的 AJAX 调用检索数据。
- 问题在于检索到的数据包含用于组成一些我需要的链接的信息。
让我给你看代码并一步步注释它:
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>
);
}
}
非常感谢您;)
【问题讨论】:
-
天哪,混合 jquery 和 react...你在做什么 m8 ?
-
不要混合使用 jQuery 和 React。这样做没有充分的理由,只会让你头疼。选择其中一个并坚持下去。我保证有一种方法可以让你用纯 React 完成所有你想做的事情。也许您可以详细说明您正在尝试做的什么,您想要的结果,我们可以从那里开始。如果你只是想很好地呈现一个表格,那么有 React 库可以做到这一点,或者你可以自己制作......
-
感谢您的建议,只是将 jQuery 用于 AJAX 调用之类的一些事情......没什么大不了的。这里的问题不是 jQuery,而是如果编写 JSX 来在 componentDidMount 中组合 组件是不可能的......你能帮我解决这个问题吗?
-
一个专业的使用 React 的网站(或者实际上是 2017 年的任何网站)不会在任何地方使用 jQuery。此外,在组件内部获取数据以以这种方式操作它们是一种反模式。您希望发出将在其他地方发起网络请求的操作/事件,并让这些流自上而下通过您的应用程序产生的状态更改。
-
好的,谢谢大家。正如我在问题中所说,我只是在学习 React,我知道我不知道它在幕后是如何工作的。
标签: javascript reactjs react-router frontend