【问题标题】:Is there no way to run an AJAX script inside a React Component?有没有办法在 React 组件中运行 AJAX 脚本?
【发布时间】:2019-08-07 22:59:01
【问题描述】:

我可以找到(在线)导入 ajax 的唯一方法是通过 HTML 脚本标签 <script ... </script>,但我的 webapp 是在没有 HTML 文件的情况下构建的。这是一个奇怪的情况,因为我已经制作了一个(带有一些重要的东西,如网站图标参考和网站名称),但是无论我的应用程序如何设置,它似乎并不关心 index.html。

它是使用 Koa、Next、React 和 Material-UI 构建的。我绝不是专业人士,但我在以前使用 Koa、Next 和 React 构建的应用程序之后建模了这个应用程序,该应用程序确实有一个正常运行的 index.html,但该应用程序在没有它的情况下工作,我仍然无法弄清楚生活我的代码应该在何时/何地要求它。最好的情况是我不需要 index.html 来使 AJAX 工作,但是 如果有人知道我在让 index.html 工作时缺少什么,我会全力以赴强>.

这是我的存储库目前的样子:

[-components
[---Component1
[---Component2
[---Component3
[---Component...
[-node_modules
[-pages
[---index.js
[-public
[---favicon.png
[---index.html
[-app.js
[-package.json

有问题的代码是@index.js

class Index extends React.Component {
    state = {
        loading: false,
    };

    componentDidMount() {
        var jqXHR = $.ajax({
            type: "POST",
            url: "/login",
            async: false,
            data: { mydata: [Cookies.get('links'), Cookies.get('numSentences')] }
        });
        Cookies.set('final', jqXHR.responseText);
    }

    handleClickLoading = () => {
        this.setState(state => ({
            loading: true,
        }));
        this.componentDidMount();
    };

    render() {
        const {loading} = this.state;
        return (
            <div>
                <AppBar/>
                <Block/>
                <Card>
                    <CardActions>
                    <Button size="large"
                            fullWidth={true}
                            onClick={this.handleClickLoading}>Submit</Button>
                    </CardActions>
                </Card>
                <Fade
                    in={loading}
                    unmountOnExit
                    >
                <BottomBar/>
                </Fade>
            </div>

        )
    }
}

export default Index;

此代码将在加载页面时立即崩溃,并出现ReferenceError: $ is not defined。这是在我进行了一些故障排除之后,最初在 handleClickLoading() 函数中有这样的 AJAX 代码,直到触发按钮 onClick 事件才会崩溃:

...
class Index extends React.Component {
    state = {
        loading: false,
    };

    handleClickLoading = () => {
        this.setState(state => ({
            loading: true,
        }));
        var jqXHR = $.ajax({
            type: "POST",
            url: "/login",
            async: false,
            data: { mydata: [Cookies.get('links'), Cookies.get('numSentences')] }
        });
        Cookies.set('final', jqXHR.responseText);
    };

    render() {
...

作为参考,我可以输入“$.ajax”,Pycharm 会自动完成并告诉我预期的参数,但它总是会被加下划线并标记为“缺少导入语句”。如何导入?

【问题讨论】:

标签: javascript node.js ajax koa next.js


【解决方案1】:

取而代之的是 ajax 有 axios npm 模块,它可以做同样的事情,并且可以很好地与 react 尝试 axios 它很简单然后 ajax

here is link for npm module

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 2022-01-13
    • 2019-01-17
    • 2011-09-18
    • 1970-01-01
    • 2016-03-01
    • 2019-11-18
    • 1970-01-01
    相关资源
    最近更新 更多