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



是否可以将变量值从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发布到后端。

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

您应该在constructor中的状态中添加一个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>
);
}
}

最新更新