从服务器重定向后,为React Router组件提供状态变量(使用Redux进行状态处理)



我正在使用React和Redux构建客户端应用程序,使用Node设置服务器端API端点。

对于一个功能,我想在电子邮件中发送一个令牌,然后点击链接(类似website.com/token?email=dave.example@something.com&token=3ad56gyhg(,使用服务器端API验证他们的令牌/电子邮件,然后将他们重定向到React中的特定页面(使用React路由器(。

我预计节点API会看起来像这样:

app.get('/token', (req, res, next) => {
    //code here.....
    //goes and checks the email and token code match what is in the database
    if (success) {
         res.redirect('/welcome');
    }
}

一旦我重定向到适当的React路由器端点,我如何向任何组件提供与用户相关的状态/道具?例如,我可能想在验证了他们的令牌后,在页面上使用他们的电子邮件地址。

ReactDOM.render(
<Provider store={store}>
    <Router history={hashHistory}>
        <Route component={App}>
            <Route path="/" component={EntryPoint} />
            <Route path="/welcome" component={WelcomeContainer} />
        </Route>
    </Router>
</Provider>,
document.getElementById('root')
);

我是否必须走同构的路线,在服务器上创建一个存储?组件是否需要返回并从服务器获取"初始状态"?

您有一个静态HTML/CSS/JS服务器,并且有一个Nodeneneneba API。在这种情况下,您无法对发送到客户端的HTML进行"模板化"。这意味着您只能通过URL参数将数据传递给react应用程序。

app.get('/token', (req, res, next) => {
    //code here.....
    //goes and checks the email and token code match what is in the database
    if (success) {
         res.redirect(`/welcome/${encodeURIComponent(email)}`);
    }
}

然后,当您的组件加载时,检查查询参数:

ReactDOM.render(
<Provider store={store}>
    <Router history={hashHistory}>
        <Route component={App}>
            <Route path="/" component={EntryPoint} />
            <Route path="/welcome/:email" component={WelcomeContainer} />
        </Route>
    </Router>
</Provider>,
document.getElementById('root')
);

备选方案:

  • /token重定向到您的网络应用程序
  • 您的react应用程序现在接收电子邮件&令牌参数,然后用电子邮件向CCD_ 3发出API请求&令牌参数
  • 您的应用程序处理API请求(返回成功/失败(,然后在内部重定向到/welcome

这是我通常做这件事的方式。关键是要确保当用户点击验证链接时,他们会被直接带到网络应用程序。网络应用程序执行API验证业务。

最新更新