使用 React 渲染来自 Express 的 Flash 消息

HPJ*_*PJM 3 express reactjs

我已经搜索了很多,但一直无法找到一种简单的方法来从 Express 获取 Flash 消息并在 React 中呈现它们。

我需要访问 Express 服务器上的数据,但是存储这些数据并将其传递给 React 的最佳方法是什么?我想在index.html呈现React文件时传递一个对象,但我不确定如何访问这些数据,或者在发生某些事件时发送正确的数据,例如用户输入错误的密码。

HPJ*_*PJM 5

我解决了这个问题。

我的会话中有一个名为 flash 的变量,默认设置为 false。

在护照流程的正确部分,我根据错误将其重新定义为字符串。我有一个 React 动作和 reducer 来获取这些数据,如果它是真的,就把它渲染到屏幕上。当组件卸载或站点刷新时,我将其重置为 false。

编辑:我找到了一个更好的解决方案

1. 如果出现问题,请在通行证中间件中设置可选消息。

return done(null, false, { message: 'Email not found' });
Run Code Online (Sandbox Code Playgroud)

2. 在login路由中发送此信息作为响应。

router.post('/login', (req, res, next) => {

    passport.authenticate('local-login', (e, user, info) => {
        if(e) return next(e);
        if(info) return res.send(info);
        req.logIn(user, e => {
            if(e) return next(e);
            return res.send(user);
        });
    })(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)

3. 在 Redux 动作生成器中处理提交和响应。如果用户进行身份验证,则消息属性将是未定义的。

const res = await axios.post('/auth/login', { email, password });

dispatch({
    type: 'FLASH',
    payload: res.data.message
});
Run Code Online (Sandbox Code Playgroud)

4.在reducer中,状态要么是字符串要么是假:

return action.payload || false;
Run Code Online (Sandbox Code Playgroud)

5. 然后就是把状态渲染到屏幕上的问题了。当组件卸载以重置状态时,可以发送另一个操作。

希望这可以帮助其他人。