javascript - 在 React 中单击按钮时调用 Api post 方法

标签 javascript reactjs asp.net-web-api

我有一个如下所示的事件:

    handleDownload(e) {
    e.preventDefault();
    alert('Hi');
    let communityName = this.state['selectedCommunity'];
    let files = this.state[files];

    fetch(clientConfiguration['filesApi.local'], {
        method: 'POST',
        headers: new Headers(),
        body: JSON.stringify({ communityName: communityName, body: files })
    }).then((res) => res.json())
        .then((data) => console.log(data))
        .catch((err) => console.log(err))
};

我有一个按钮如下:

    renderDownloadButton() {
    if (this.state.files && this.state.files.filter(i => i.checked).length) {
        return (
            <button id="download" styles="display: none;" onClick={this.handleDownload} >
                Download
    </button>
        );
    }
};

它会触发,但出现以下错误,请提供帮助 - 谢谢。在

let communityName = this.state['selectedCommunity'];

它给了我错误;

Can not read property state undefined

请问有什么帮助吗?

最佳答案

我的猜测是您需要绑定(bind)处理程序,但如果没有完整的组件代码,真的很难判断。

handleDownload = (e) => {
    e.preventDefault();
    alert('Hi');
    let communityName = this.state['selectedCommunity'];
    let files = this.state[files];

    fetch(clientConfiguration['filesApi.local'], {
        method: 'POST',
        headers: new Headers(),
        body: JSON.stringify({ communityName: communityName, body: files })
    }).then((res) => res.json())
        .then((data) => console.log(data))
        .catch((err) => console.log(err))
}

关于javascript - 在 React 中单击按钮时调用 Api post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331499/

相关文章:

javascript - 带组合框的 ExtJS 分页

reactjs - Jest 单元测试 - 如何模拟表行图标的单击事件

c# - 通过 ASP.NET 应用程序上传大文件(最大 100gb)

asp.net - 如何在不查找 AspNetUserRoles 表的情况下在 Web API 方法中获取用户角色?

asp.net-web-api - UriPathExtensionMapping 以控制 WebAPI 中的响应格式

java - 是否可以在 ie 中从 JavaScript 创建任意 Java 对象?

javascript - JS中如何取消网络请求?

javascript - 如何在 react-vis 中反转/下降/排序 x 轴数据

javascript - 如何更改 <select> 元素上的背景图像

javascript - 通过使用 aws-sdk 在 s3 Bucket 上上传图像来 react native