如何最好地听取 POST 响应?

How to best to listen for POST response in react?

我有一个表单中的数据,我想将其加载到数据库中,并根据状态将它们保留在页面上或将它们移动到不同的页面。

目前我在表单上附加了以下功能。

const handleSubmit = (e) => {
        e.preventDefault();
        const topic = {id, title, desc, text};
    
        console.log(topic);
        
        const isSuccess = commitData(topicsEndPoint, topic)
        console.log(isSuccess)
        if (isSuccess) {
            history.push(endPoint)
        } else {
            setError("An error has occured.")
        }
    }

而 commitData 是 运行 这样的...

export const commitData = (endPoint, data) => {
    let isSuccess = false;

    fetch(endPoint, {
        method: 'POST',
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify(data)
    })
    .then(e => {
        if (!e.ok) {
            throw(e)
        }
        isSuccess = true;
        console.log(isSuccess)
        return isSuccess
    })
    .catch(err => {
        isSuccess = false;
        console.log(isSuccess)
        return isSuccess
    })
}

我相信如果我将历史记录和重定向页面传递到 commitData 中,我可以让它工作,但它开始变得比已经看起来的功能更麻烦。

现在这行不通,因为 handleSubmit 在继续之前不会等待响应返回。

我认为使用钩子是可行的方法,但 React 不喜欢它,因为我把它放在里面 handleSubmit 但即使我将它大写 HandleSubmit 它也不喜欢它。

我正在寻找最佳实践。

(我试过 awaitthen 附加到 commitData 但它不喜欢语法)

使handleSubmit()异步:

const handleSubmit = async (e) => {
        e.preventDefault();
        const topic = {id, title, desc, text};
    
        console.log(topic);
        
        const isSuccess = await commitData(topicsEndPoint, topic)
        console.log(isSuccess)
        if (isSuccess) {
            history.push(endPoint)
        } else {
            setError("An error has occured.")
        }
    }