当页面重定向到另一个页面时,React toastify 不起作用。但它正在同一页面上工作

MAY*_*KUR 4 reactjs react-notifications

我使用react-toastify进行toast通知,但是当我的页面重定向到另一个页面时它不起作用。

mydata 无法保存到数据库。当我的页面没有重定向时它正在工作。

const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

const loginUser = async (e) => {
    e.preventDefault();
    const res = await fetch("/signin", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ email, password }),

    });

    const data = await res.json();
    if (res.status === 422 || !res) {
        warningAlert();
        console.log(res);
        console.log("Invalid Credentials")
    } else {
        successAlert();
        dispatch({ type: "USER", payload: true });
        // console.log(res);
        history.push("/");

    }
}
Run Code Online (Sandbox Code Playgroud)

以上代码用于登录。这里的通知不是在else条件下工作,而是在条件下工作if

上述警报

    const successAlert = () => {
    // window.alert("Invalid Credentials");
    toast("User logged in successfully", {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: false,
        draggable: true,
        progress: undefined,

    });
}


    const warningAlert = () => {
    // window.alert("Invalid Credentials");
    toast.error("Invalid Credentials", {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: false,
        draggable: true,
        progress: undefined,

    });
}
Run Code Online (Sandbox Code Playgroud)

小智 8

您必须<ToastContainer/>在项目的根目录中使用,以便可以从所有页面访问该容器。然后调用函数

官方文档


Fir*_*iki 5

就我而言,这是window.location.href = '/user'我在创建用户后用于转到主页的。这将导致整个应用程序重新加载(重置),因此无论您将组件保存在何处,通知都将不起作用<ToastContainer/>

确保您使用react-router方法(history.push或navigate)来更改路由。