摘要:
我正在尝试使用(react toast ify(在通知(toast(中显示来自控制器(后端(的消息。然后,每当我尝试用错误的电子邮件登录(点击登录按钮(时,就会出现一个toast,其中包含一条我们可以在控制器文件中找到的消息(例如:"有电子邮件的用户不存在"或"请输入所有字段"(。。。消息当然可以根据status
或message
而变化。
- 我的代码(返回(:
back/controllers/user.js:
login: (req, res) => {
const { email, password } = req.body
if (!email || !password)
return res.status(400).json({ message: 'Please enter all fields' }) <=== this is the message i want to display in toast.
User.findOne({ email }, async (err, user) => {
if (!user) {
res.status(403).json({ message: 'User with email does not exist' }) <=== this is the message i want to display in toast.
console.log('wrongmail');
} else {
const ismatch = await bcrypt.compare(password, user.password)
if (ismatch) {
console.log('ismatch');
const token = signToken(user._id, user.role);
res.cookie("access_token", token, { maxAge: 3600 * 1000, httpOnly: true, sameSite: true });
return res.status(200).json({ isAuthenticated: true, role: user.role })
} else {
res.status(403).json({ message: 'Invalid password !' }) <=== this is the message i want to display in toast.
}
}
})
},
- 我的代码(前端(:
Front/src/views/Login/index.jsx:
import React, { useState } from 'react'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
export default () => {
const notify = () => toast(""); <=== What should i put here to be rendred?
return (
<div className="col-lg-6">
<fieldset>
<input value={email} onChange={(e) => setemail(e.target.value)} type="text" name="email" id="email" pattern="[^ @]*@[^ @]*" placeholder="Your Email" required />
</fieldset>
<fieldset>
<input value={password} onChange={(e) => setpassword(e.target.value)} type="password" name="password" id="subject" placeholder="password" autoComplete="on" />
</fieldset>
<fieldset>
<button type="submit" id="form-submit" className="main-button" onClick={notify}>Login</button>
<ToastContainer />
</fieldset>
</div>
)
}
我在Login/index.jsx中添加了我在这里找到的要点代码:https://fkhadra.github.io/react-toastify/installation,但我无法找到一种方法来调用控制器文件(BE(中的任何消息来呈现,正如我在总结中最初解释的那样。
您应该在从BE获得响应的函数中使用toast方法。例如:
getUserDetails() {
//call backend here
try {
const data = result_from_backend
toast.success('your toast message')
} catch (e) {
toast.error('show the error here');
}
}