如何在组件之间传递状态变量

时间:2020-05-22 01:39:47

标签: reactjs

我正试图将'year'状态变量传递给Playlist类;到目前为止,当用户在填写完输入后按Enter键时,该输入将保存在Class Home的状态变量“ year”中,但是我需要将其传递给Playlist类,而我在网上发现的内容不适合它据我所见/尝试。

class App extends Component {   
  render() {    
    return (
      <Router>
        <div className='App'>
          <Route exact path = '/' component= {Home}/>
          <Route path= '/playlist' component = {Playlist}/>
        </div>
      </Router>
    ); 
  }
}
export default App;

class Home extends Component {
      constructor(props){
         super(props);
         this.state = {
            year: ' '
         };
         this.handleSubmit = this.handleSubmit.bind(this);
         this.updateInput = this.updateInput.bind(this);
      }

      updateInput(event){
         this.setState({year : event.target.value})
      }

      handleSubmit(event){
         alert("Year Submitted");
         this.props.history.push('/playlist');
         event.preventDefault();
      }
  render() {    
     return (
        <div id="body" className="Home">
            <div>
              <form onSubmit={this.handleSubmit}>
                 <input id = "yearInput" autoComplete="off" type="text" placeholder = 
                "Enter Year" onChange={this.updateInput} />
              </form>
            </div>
        </div>
     );
  }
}
export default Home;

class Playlist extends Component{
    constructor(props) {
       super(props);
       this.state = {
         year: ' '
       };
        this.goingBack = this.goingBack.bind(this);
    }

    goingBack(){
        console.log(this.year);
        this.props.history.push("/");
    }

    render(){
        return (
            <div className="Playlist">
                <h1> Playlist </h1>
                <div>
                    <button onClick={this.goingBack}> Go back </button>
                </div>

            </div>
        );
    }
}
export default Playlist;

1 个答案:

答案 0 :(得分:1)

您可以通过路线状态。假设两者都直接由Route组件呈现,那么两者都可以访问route-props

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      year: ' '
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateInput = this.updateInput.bind(this);
  }

  updateInput(event) {
    this.setState({ year: event.target.value })
  }

  handleSubmit(event) {
    alert("Year Submitted");
    this.props.history.push({ // <-- use object form of push
      pathname: '/playlist',
      state: { year: this.state.year },
    });
    event.preventDefault();
  }

  render() {
    return (
      <div id="body" className="Home">
        <div>
          <form onSubmit={this.handleSubmit}>
            <input id="yearInput" autoComplete="off" type="text" placeholder=
              "Enter Year" onChange={this.updateInput} />
          </form>
        </div>
      </div>
    );
  }
}

您可以通过this.props.location.state

访问路线状态
class Playlist extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // If user navigates directly to "/playlist" state object
      // is undefined, so use a guard to protect against "access
      // ... of undefined..." errors. Also provide a default/fallback
      // value, i.e. the empty string ''.
      year: (props.location.state && props.location.state.year) || '';
    };
    this.goingBack = this.goingBack.bind(this);
  }

  goingBack() {
    console.log(this.state.year); // <--- Update to this.state.year!!
    this.props.history.push("/");
  }

  render() {
    return (
      <div className="Playlist">
        <h1> Playlist </h1>
        <div>
          <button onClick={this.goingBack}> Go back </button>
        </div>

      </div>
    );
  }
}

export default Playlist;

Edit simple route state