简体   繁体   English

React.js将prop状态从同级转移到其他同级?

[英]React.js transferring prop state from sibling to a different sibling?

I'm extremely new to react and javascript so I'm sorry if I'm asking this wrong. 我对JavaScript和JavaScript的反应是非常陌生的,因此如果我问错了,请对不起。 This is for a group project which means I most likely don't understand the project 100% 这是针对小组项目的,这意味着我很可能不理解该项目100%

  • The older sibling has this nice prop that I want to use: 年长的兄弟姐妹拥有我要使用的一个不错的道具:

``` ```

export default class OlderSibling extends Component {
  state = {
    currentCity: city //(that was gathered from a bunch of other steps)
  };

  render() {
     return(
      )
  }
}

``` ```

  • The parent file doesn't have this prop, but it does have its own stuff. 文件没有这个道具,但是它有自己的东西。 I do not care for these other props though. 但是我不关心其他道具。

``` ```

class Parent extends Component {
   constructor(props) {
     super(props)
     this.state = {
          flower: 'red'
     }
    }

 render() {
    return (
         <OlderSibling/>
         <YoungerSibling/>
    )
  }
}

``` ```

  • The younger sibling (the one that wants current city) has a bunch of this.state properties that I do not want to share with others but just want the older sibling's stuff (I guess like what younger siblings normally do). 年轻的兄弟姐妹 (想要当前城市的兄弟姐妹 )有很多this.state属性,我不想与其他人共享,而只是想要年长的兄弟姐妹的东西(我想就像年轻的兄弟姐妹通常所做的那样)。

``` ```

   export class YoungerSibling extends Component {
     constructor(props) {
        super(props);
        this.state = {
              title: '',
              description: []
         }
     }

    render() {
          return(

           )
     }
}

``` ```

Just in case I wasn't clear, younger sibling just wants older sibling's this.state: currentCity that older Sibling worked so hard to gather. 以防万一,我不清楚,年轻的兄弟姐妹只是想要年长的兄弟姐妹的this.state:currentCity,所以年老的兄弟姐妹很难收集。

I know I didn't put the code completely, but if you want to critique it anyway, please do! 我知道我没有完全放入代码,但是如果您仍然想批评它,请这样做! I am still learning and I welcome every bit of feedback! 我仍在学习中,欢迎大家提供反馈!

I looked up ways to do this, but they're all about transferring parent to child which is not what I want. 我查找了执行此操作的方法,但是它们都是关于将父母移交给孩子,这不是我想要的。 I also read that there was Redux that could handle this?? 我还读到有Redux可以解决这个问题? I don't know if my fellow groupmates are interested in that just yet. 我不知道我的同伴是否对此感兴趣。

Thank you for your time in reading this! 感谢您的阅读时间!

EDIT: 编辑:

[ SOLVED ] [ 解决了 ]

I just want to edit and say thank you to @soupette, @Liam, @[Denys Kotsur], and @Tomasz for helping me to understand react a bit more. 我只想对@ soupette,@ Liam,@ [Denys Kotsur]和@Tomasz表示感谢,感谢他们帮助我更多地了解了自己的反应。 I realize that this post was very much a spoon feeding request and you all helped away. 我意识到这篇文章非常需要勺子喂食,大家都帮了忙。 Thank you! 谢谢!

Also, just in case anybody else ran into this issue, don't forget to call it on Younger Sibling as this.props.currentCity . 此外,以防万一其他人遇到此问题,请不要忘记在Younger Sibling this.props.currentCity其称为this.props.currentCity

You can do something like: 您可以执行以下操作:

class Parent extends Component {
  state = {
     flower: 'red'
     currentCity: '',
   };

   updateCurrentCity = (currentCity) => this.setState({ currentCity });

   render() {
     return (
       <OlderSibling updateCurrentCity={this.updateCurrentCity} />
       <YoungerSibling city={this.state.currentCity} />
     );
   }
}

then in your OlderSibling you can update the parent's state with a function: 然后在您的OlderSibling中,您可以使用以下函数更新父级的状态:

export default class OlderSibling extends Component {
  state = {
    currentCity: city //(that was gathered from a bunch of other steps)
  };

  componentDidUpdate(prevProps, prevState) {
    if (prevState.currentCity !== this.state.currentCity) {
      this.props.updateCurrentCity(this.state.currentCity);
    }
  }

  render() {
    return(
    );
  }
}

You should create Parent component for these two ones and keep state there. 您应该为这两个组件创建Parent组件,并在那里保持状态。

Also, you should pass it into two children ( YoungerSibling and OlderSibling ) as a prop and add inverse data flow for OlderSibling so when city is changed in the OlderSibling then ParentSibling should know about this. 此外,你应该把它传递到两个孩子( YoungerSiblingOlderSibling )作为prop ,并添加逆数据流的OlderSibling所以当城市在改变OlderSibling然后ParentSibling应该知道这一点。

For example: 例如:

Parent.jsx Parent.jsx

  class Parent extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        currentCity: ''
      }
    }

    currentCityChangeHandler = city => {
      this.setState({currentCity: city});
    };

    render() {
      const { currentCity } = this.state;

      return(
        ...
        <OlderSibling 
            currentCity={currentCity}  
            onCurrentCityChange={this.currentCityChangeHandler} 
        />
        <YoungerSibling currentCity={currentCity} />
        ...
      )
    }
  }

OlderSibling.jsx OlderSibling.jsx

  class OlderSibling extends React.Component {
    ...

    // Somewhere when new city is coming from
    // You should pass it into the callback
    newCityComingFunction() {
      const city = 'New York';

      // Pass the new value of city into common `Parent` component
      this.props.onCurrentCityChange(city);
    }

    ...
  }

So in this case it will allow you to use this param in both cases and it will be keep updated. 因此,在这种情况下,它将允许您在两种情况下都使用此参数,并且将保持更新。

In addition, you should use this.props.currentCity in the OlderSibling instead of using this.state.currentCity in this component because it's value is moved into Parent 's component state. 此外,你应该使用this.props.currentCityOlderSibling而不是使用this.state.currentCity在这个部分,因为它的值被移动到Parent的组件状态。

Hope it will helps. 希望它会有所帮助。

As the previous answer suggests lift the state up I also prefer to use it 正如先前的答案所暗示的那样,我也更喜欢使用它

Here's an example 这是一个例子

编辑l5l18v19m9

You got two choices. 您有两个选择。

  1. use external state management library like redux. 使用像redux这样的外部状态管理库。
  2. lift the state up - which means Parent component will hold currentCity in the state. 提升状态 -这意味着Parent组件将把currentCity保持在该状态。

There could be 3rd option of using contex API but I'm not sure how to do it here. 使用contex API可能有第三种选择,但是我不确定如何在此处执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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