簡體   English   中英

ReactJS 中的“分配給常量變量”錯誤

[英]Error “Assignment to constant variable” in ReactJS

我確實遵循了如何將 mailchimp 與節點后端集成的教程。 我從來沒有碰過后端,所以很蹩腳。 當我發布到他們的 API 時,我得到了訂閱者的憑據,但我得到了一個錯誤返回 - “分配給常量變量”。 通讀 web 和其他 SO 問題,似乎我正在嘗試重新分配 CONST 值。

我看了看我的代碼,我唯一注意到的可能是這里的問題

request(options, (error, response, body) => {


    try {
            const resObj = {};
            if (response.statusCode == 200) {
                resObj = {
                    success: `Subscibed using ${email}`,
                    message: JSON.parse(response.body),
                };
            } else {
                resObj = {
                    error: ` Error trying to subscribe ${email}. Please, try again`,
                    message: JSON.parse(response.body),
                };
            }
            res.send(respObj);
        } catch (err) {
            const respErrorObj = {
                error: " There was an error with your request",
                message: err.message,
            };
            res.send(respErrorObj);
        }
    });

我注意到我正在創建一個名為"resObj"的空 object ,然后嘗試為其分配一個值。 我嘗試將CONST更改為LET ,但我收到一條錯誤消息: "resObj is not defined"

這是我的前端代碼:

 import React, { useState } from "react";
import "./App.css";
import Subscribe from "./components/Subscribe";
import Loading from "./components/Loading/Loading";
import axios from "axios";
import apiUrl from "./helpers/apiUrl";

function App() {
    const [loading, setLoading] = useState(false);
    const [email, setEmail] = useState("");

    const handleSendEmail = (e) => {
        setLoading(true);
        console.log(email);
        axios
            .post(`${apiUrl}/subscribe`, { email: email })
            .then((res) => {
                if (res.data.success) {
                    alert(`You have successfully subscribed!, ${res.data.success}`);
                    setEmail("");
                    setLoading(false);
                } else {
                    alert(`Unable to subscribe, ${res.data.error}`);
                    console.log(res);
                    setLoading(false);
                    setEmail("");
                }
            })
            .catch((err) => {
                setLoading(false);
                alert("Oops, something went wrong...");
                console.log(err);
                setEmail("");
            });
        e.preventDefault();
    };

    const handleInput = (event) => {
        setEmail(event.target.value);
    };

    // const handleLoadingState = (isLoading) => {
    //  setLoading({ isLoading: loading });
    //  console.log(loading);
    // };
    return (
        <div className='App'>
            <h1>Subscribe for offers and discounts</h1>

            {loading ? (
                <Loading message='Working on it...' />
            ) : (
                <Subscribe
                    buttonText='Subscribe'
                    value={email}
                    handleOnChange={handleInput}
                    handleOnSubmit={handleSendEmail}
                />
            )}
        </div>
    );
}

export default App;

和后端代碼:

const restify = require("restify");
const server = restify.createServer();
const corsMiddleware = require("restify-cors-middleware");
const request = require("request");
require("dotenv").config({ path: __dirname + "/variables.env" });

const subscribe = (req, res, next) => {
    const email = req.body.email;
    const dataCenter = process.env.DATA_CENTER;
    const apiKey = process.env.MAILCHIMP_API_KEY;
    const listID = process.env.LIST_ID;

    const options = {
        url: `https://${dataCenter}.api.mailchimp.com/3.0/lists/${listID}/members`,
        method: "POST",
        headers: {
            "content-type": "application/json",
            Authorization: `apikey ${apiKey}`,
        },
        body: JSON.stringify({ email_address: email, status: "subscribed" }),
    };

    request(options, (error, response, body) => {
        try {
            const resObj = {};
            if (response.statusCode == 200) {
                resObj = {
                    success: `Subscibed using ${email}`,
                    message: JSON.parse(response.body),
                };
            } else {
                resObj = {
                    error: ` Error trying to subscribe ${email}. Please, try again`,
                    message: JSON.parse(response.body),
                };
            }
            res.send(respObj);
        } catch (err) {
            const respErrorObj = {
                error: " There was an error with your request",
                message: err.message,
            };
            res.send(respErrorObj);
        }
    });
    next();
};

const cors = corsMiddleware({
    origins: ["http://localhost:3001"],
});

server.pre(cors.preflight);
server.use(restify.plugins.bodyParser());
server.use(cors.actual);
server.post("/subscribe", subscribe);

server.listen(8080, () => {
    console.log("%s listening at %s", server.name, server.url);
});

如果有人可以提供幫助,我將不勝感激。 訂閱表格有效,但我需要清除該錯誤,以便我的前端在提交表格時正常工作。

也許您正在尋找的是Object.assign(resObj, { whatyouwant: value} )

這樣您就不會重新分配resObj引用(因為resObj是 const,所以無法重新分配),而只是更改其屬性。

參考 MDN 網站

編輯:此外,而不是res.send(respObj)你應該寫res.send(resObj) ,這只是一個錯字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM