bugfix> javascript > 投稿

Reactバージョン15.2.1 誰かがコンポーネント間でデータをやり取りする方法を教えてください。 Login.jsのメールとパスワードをProducts.jsに渡す必要があります。ここで、関数display()でサーバーにhttpリクエストを送信しています。

Login.js

   import React from "react";
    import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
export class Login extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        email: "",
        password: ""
    };
}
validateForm() {
    return this.state.email.length > 0 && this.state.password.length > 0;
}
handleChange = event => {
    this.setState({
        [event.target.id]: event.target.value
    });
}

handleSubmit = async event => {
    event.preventDefault();
    try {
        this.props.history.push("/products");
    } catch (e) {
        alert(e.message);
    }
}
render() {
    return (
     <div className="Login">
        <form onSubmit={this.handleSubmit}>
            <FormGroup controlId="email" bsSize="large">
                <ControlLabel>Email</ControlLabel>
                <FormControl
                    autoFocus
                    type="email"
                    value={this.state.email}
                    onChange={this.handleChange}
                />
            </FormGroup>
            <FormGroup controlId="password" bsSize="large">
                <ControlLabel>Password</ControlLabel>
                <FormControl
                    value={this.state.password}
                    onChange={this.handleChange}
                    type="password"
                />
            </FormGroup>
            <Button
                block
                bsSize="large"
                disabled={!this.validateForm()}
                type="submit"
            >
                Login
            </Button>
        </form>
    </div>
   );
  }
}

Products.js

   import React from 'react';
    export class Products extends React.Component {
display(){
    var http = new XMLHttpRequest();
    var url = ""
    //have hardcoded username and password here for now. need to get it from Login component
    http.send()
    return http.responseText
}
render() {
    var x=this.display();
    var jsonObject = JSON.parse(x)
    // console.log(jsonObject)
    var conArray=[]
    for (var y=0; y < jsonObject.length; y++){
        console.log(jsonObject[y]['completeName'])
        conArray.push(jsonObject[y]['completeName'])
    }
    return (
        <div>
            <h2>Product Names</h2>
            {
                conArray.map(t => <div>{t}</div>)
            }
        </div>
    );
  }
}

index.js

   import React from 'react';
    import { render } from 'react-dom';
    import {BrowserRouter as Router} from "react-router-dom";
    import Route from 'react-router-dom/Route';
    import { browserHistroy, Switch } from 'react-router';
    import createBrowserHistory from 'history/createBrowserHistory';
    const newHistory = createBrowserHistory();
    import { Products } from "./components/Products";
    import { Login } from "./components/Login";
    import "babel-polyfill";
    class App extends React.Component {
render() {
    return (
       <Router history={newHistory}>
           <Switch>
               <Route path="/" exact component={Login}/>
               <Route path="/products" exact component={Products}/>
           </Switch>
       </Router>
    );
}
}
render(<App />, window.document.getElementById('app'));

回答 1 件
  • それを行う1つの方法は、小道具を state variable に渡すことです。  歴史の  このようなもの:

       this.props.history.push({
      pathname: '/products',
      state: { email: this.state.email,
               password: this.state.password }
        })
    
    

    this.props.location.state.email を使用してproducts.jsでこれらにアクセスできます  および this.props.location.state.password  もう1つは、product.jsコンポーネントを withRouter でラップすることを忘れないでください  接続して /products の値を使用できるようにする

あなたの答え