gpt4 book ai didi

node.js - 将变量值从react构造函数传递到nodeJS后端

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:28 24 4
gpt4 key购买 nike

是否可以将变量值从 React 构造函数发布到 Nodejs 后端。我们希望在页面加载到 Nodejs 时发布某些数据并在后端执行某些功能。

constructor(props) {
super(props);
const tokenFetch = localStorage.getItem("JWT");
const nameFetch = localStorage.getItem("Name");
this.state = {
userLoggedIn,
name: nameFetch,
tokenFetch: tokenFetch
};
}

在构造函数中,我们希望将 name 和 tokenFetch 发布到后端。

最佳答案

根据构造函数中HTTP请求的响应来决定某些元素是否应该呈现是一个坏主意。您不希望页面“挂起”,因为请求花费的时间比您预期的要长。

您应该向构造函数中的状态添加一个boolean标志,并基于此标志渲染您想要或不想渲染的元素。然后,您可以在 componentDidMount 方法中执行您的 HTTP 请求,然后更改标志:

class MyComponent extends React.Component {

constructor(props) {
super(props);
const tokenFetch = localStorage.getItem("JWT");
const nameFetch = localStorage.getItem("Name");
this.state = {
responseFromServerReceived: false,
userLoggedIn,
name: nameFetch,
tokenFetch: tokenFetch
};
}

componentDidMount() {
axios({
method: 'post',
url: '/whereYouWantToSendData',
data: { firstName: this.state.nameFetch, token: this.state.tokenFetch }
}).then(response => {
// Whatever you want to do with the response;
this.setState({ responseFromServerReceived: true });
});
}

render() {
const elementToRender = this.state.responseFromServerReceived
? <h1>Hello, the response of the server was received.</h1>
: <h1>Hello, the response of the server was NOT received yet.</h1>;

return (
<div>
{elementToRender}
</div>
);
}
}

关于node.js - 将变量值从react构造函数传递到nodeJS后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60427877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com