有没有办法在React组件中运行AJAX脚本?

问题描述 投票:1回答:1

我可以找到(在线)导入ajax的唯一方法是通过HTML脚本标记<script ... </script>,但我的webapp是在没有HTML文件的情况下构建的。这是一个奇怪的情况,因为我已经制作了一个(有一些重要的东西,如favicon参考和网站名称),但是我的应用程序设置,它似乎并不关心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加载页面时,此代码将立即崩溃:$未定义。这是在我进行了一些故障排除后,最初在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将自动完成并告诉我预期的参数,但它总是被加下划线并标记为“缺少import statement”。我该如何导入它?

javascript node.js ajax koa next.js
1个回答
0
投票

相反ajax有axios npm模块,它做同样的工作并且与反应尝试axios很好,它很简单然后ajax

here is link for npm module

© www.soinside.com 2019 - 2024. All rights reserved.