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

问题描述 投票:0回答:1

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

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

在这里,我们要在构造函数中将名称和tokenFetch发布到后端。

node.js reactjs express react-router router
1个回答
0
投票

根据构造器中HTTP请求的响应来确定是否应渲染某些元素是一个坏主意。您应该向状态添加一个布尔值标志,并基于该标志来渲染您想要或不希望渲染的元素。然后,您可以在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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.