【问题标题】:How to pass a state variable between components如何在组件之间传递状态变量
【发布时间】:2020-05-22 01:39:47
【问题描述】:

我正在尝试将“年份”状态变量传递给 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;

【问题讨论】:

  • 如果Home和Playlist是兄弟组件,你可以lift up the state。或者,您可以使用Context 或Redux 来解决此问题。
  • 渲染播放列表的是什么组件?我的假设是 Home 是父组件,因此您只需将 year 作为道具传递。
  • 播放列表正在输入标签上的 handleSubmit(event) 上呈现。所以 Home 是父组件,是的,我试图将年份作为道具传递,但不确定@DannyMoshe 是如何
  • 那么有一个路由器可以渲染主页和播放列表吗?当你渲染 Home 组件时,你传递一个函数来设置路由器的状态。然后在路由器中,当您渲染播放列表组件时,您从路由器的状态中获取状态。只是猜测,因为我看不到您的所有代码。
  • 显示 Home 和 Playlist 组件的实际呈现位置会很有帮助。 Home 不会呈现播放列表,只是在 /Playlist 路由上发出请求。

标签: reactjs


【解决方案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;

【讨论】:

  • 我尝试了您所做的更改,尽管它是有道理的,来自 Playlist 类的 goBack() 函数中的 console.log(this.props.year) 不会记录我输入的输入在 Class Home 的输入标签中
  • @surpol goingBack 中存在复制/粘贴错误,应为 this.state.year。我在制作要添加到 asnwer 的代码沙盒演示时发现了它。现在更新了。
  • 谢谢!有效;除了解除状态之外,我在任何地方都找不到解决方案,并且正在寻找替代方案
  • @surpol 我曾考虑过提升状态和/或使用全局状态(redux/react 上下文)将有助于解决路由状态的瞬态性质,但看到您基本上只是在字段中输入文本并导航假设您不是在寻找更永久的状态值。如果充分解决了您的问题,请随时接受,如果您觉得有帮助,请点赞。
猜你喜欢
  • 2022-10-12
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 2021-09-13
  • 2013-11-03
  • 2020-05-16
相关资源
最近更新 更多