简体   繁体   中英

How to pass a variable from one page to another in ReactJS?

I have exported multiple variables, but the method I'm using for storing this one does not seem to work for some reason. I have login page, which stores the correct value into "ID" as shown below

import AuthService from './AuthService';

let ID = "";


class LoginPage extends Component {
  constructor(props) {
    super(props);
      this.state = {
      username: '',
      password: ''
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.Auth = new AuthService();
  }


  handleFormSubmit(e){
    e.preventDefault();

    this.Auth.login(this.state.username,this.state.password)
        .then(res =>{
          if(this.Auth.state.isA)
           this.props.history.push('/AdminApp');
          else if(this.Auth.state.isA === 0 && this.Auth.state.sub === 0)
          { 
            ID = this.Auth.state.userID;
            console.log(ID) // This prints the right value
            this.props.history.push('/SDForm')
          }
        })
        .catch(err =>{
            alert(err);
        })
  }

  handleChange = event => {
    this.setState({
      [event.target.id]: event.target.value
    });
  }

  render() {
    return (
     <Container>
        <Col className="UCFLogo"><img src={logo} /></Col>
        <Form className="LoginForm">
          <Col>
            <h1 className="mainTitles">Senior Design Project Selection</h1>
            <h3 className="subTitle">Sign In</h3>
          </Col>

          <Col>
            <FormGroup className="LoginPad">
              <Label className="subTitle">Knights Email</Label>
              <Input className="LoginInfo" type="text" name="username" id="username" onChange={this.handleChange.bind(this)} value={this.state.username} />
            </FormGroup>
          </Col>

          <Col>
            <FormGroup>
              <Label className="subTitle" for="password">Password</Label>
              <Input className="LoginInfo" type="password" name="password" id="password" onChange={this.handleChange.bind(this)} value={this.state.password} />
            </FormGroup>
          </Col>

          <Button className="subTitle" onClick={this.handleFormSubmit}>Submit</Button>

        </Form>
      </Container>
    );
  }
}

export default LoginPage;
export {ID};

Then, I need to load that ID from login into my state in my form.js file (below) in order to return it to the json upon submit, I'm just attempting to print the ID to the console until I know that I am getting the right value, and for the sake of length, I cut most of the code out, but I get this in the console

ƒ LoginPage(props) {
    var _this;

    Object(C_csform_master_node_modules_babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, LoginPage);

    _this = Object(C_cs…

form.js

import ID from './LoginPage';
const Auth = new AuthService();



class SDForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      firstName: "",
      lastName: "",
      ID: "",
    }
    this.Auth = new AuthService();
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
  }


  printToConsole = () => {
    console.log(ID) 
  }

  render() {
    return (
      <Container>
        <Form className="SDForm">

          // Form stuff


        <Col className="subTitle">
          <Button onClick={this.printToConsole}>Submit</Button>
        </Col>
      </Form>
      </Container>
    );
  }
}

export default withAuth(SDForm); 

This is not the proper way of passing information between components in React. In most cases, the best way to do it would be putting the value of ID in the Redux store or getting the ID value to them store it on a state and passing the ID state as a prop to the SDForm component, as shown next:

import SDForm from './SDForm.js'

And them (once you get your ID value and you store it on a state ):

const { ID } = this.state; 

And then in the <SDForm /> you can use ID prop as you see fit.

<SDForm id={ID} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM