简体   繁体   English

React 中组件之间的数据传输

[英]Data transfer between components in React

I'm new to react and struggling with how to transfer data from one component to another.我对如何将数据从一个组件传输到另一个组件做出反应并苦苦挣扎。

I referred some tutorials and blogs, but things aren't working for me.我参考了一些教程和博客,但事情对我不起作用。

I have two child components, Body-content.jsx and Profile.jsx and 1 parent component parent.jsx我有两个子组件Body-content.jsxProfile.jsx以及 1 个父组件parent.jsx

I want to transfer some data from Body-content.jsx to Profile.jsx .我想将一些数据从Body-content.jsx传输到Profile.jsx

Here's my code这是我的代码

Body-content.jsx


class BodyContent extends React.Component {
    componentDidMount() {
        this.getUserList()
    }
    getUserList(){
      fetch('https://jsonplaceholder.typicode.com/users')
        .then(result => {
            return result.json();
        }).then(data =>{
           this.setState({
             users : data
           })
        })
    }

      render() {
        const user = this.state.users.map((userData, i) => (          
          <CardBody>
              ...some code here
              <Button color='primary' onClick={e => this.viewProfile(userData)}>View Profile</Button>
          </CardBody>
        </Card>
        ));
          return (
            <>
       <div>{user}</div>
            </>
          )
      }

      viewProfile = function (data) {
      }
  }
  export default BodyContent;

profile.jsx

class Profile extends React.Component {
  componentDidMount() {
  }
  render() {

    return (
      <>
        <TopNav />
        <main className="profile-page" ref="main">
                    <section>
                       //code goes here
                    </section>
        </main>
      </>
    );
  }
}

export default Profile;

Store your data in parent component and send it as props to children.将您的数据存储在父组件中并将其作为道具发送给子组件。 If you have to change it in one of them, then send (also as prop) the function, which will change data in parent component.如果您必须在其中一个中更改它,则发送(也作为道具)function,这将更改父组件中的数据。

Code sample:代码示例:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {someData: ''};
  } 

  changeData(newData) {
    this.setState({
      someData: newData
    });
  }

  render() {
    return (
      <>
        <Child1 setData={this.changeData} data={this.state.someData} />
        <Child2 setData={this.changeData} data={this.state.someData} />
      </>
    )
  }
}

Both of them will be able to change data in parent component using this.props.setData('newData')他们都将能够使用this.props.setData('newData')更改父组件中的数据

If you want to share your state across the child component then you may need to move that property in parent's state which you may able to share between two child components.如果您想在子组件之间共享您的 state,那么您可能需要将该属性移动到父组件的 state 中,您可以在两个子组件之间共享该属性。

  • Sibling to Sibling兄弟姐妹
    • Parent Component父组件
  • Any to Any任意到任意
    • Observer Pattern观察者模式
    • Global Variables全局变量
    • Context语境

How to make a shared state between two react components? 如何在两个反应组件之间制作共享 state?

You can hoist state to parent component:您可以将 state 提升到父组件:

class Parent extends Component {
  state = {
    users
  };

  handleUsersChange = users => this.setState({ users });

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

    return (
      <React.Fragment>
        <Body-content onUsersChange={ this.handleUsersChange } />
        <Profile users={ users } />
      </React.Fragment>
    );
  }
}

...

class BodyContent extends React.Component {
    getUserList(){
      fetch('https://jsonplaceholder.typicode.com/users')
        .then(result => {
            return result.json();
        }).then(data =>{
           this.props.handleUsersChange(data);
        })
    }
  }

In ReactJs the data flow is uni-directional - Top-to-bottom.在 ReactJs 中,数据流是单向的 - 从上到下。 The parents passes the data to respective children.父母将数据传递给各自的孩子。

Here, since you want to share the data between two siblings.在这里,因为您想在两个兄弟姐妹之间共享数据。 The data should be first available to their parent.数据应该首先提供给他们的父母。

In order to do so, your getUserList api call should be inside of your parent, ie your parent.jsx component.为此,您的getUserList api 调用应该在您的父级内部,即您的parent.jsx组件中。

From there you can pass the data as props to both the siblings.从那里您可以将数据作为道具传递给兄弟姐妹。

Let me know if you need and further explanation to this.让我知道您是否需要对此进行进一步解释。 If needed, please share your parent.jsx code.如果需要,请分享您的parent.jsx代码。 I can help you further.我可以进一步帮助你。

Hi and welcome to the world of React,嗨,欢迎来到 React 的世界,

If you want to share data between siblings components, you should always keep in mind that you should store your data at the highest common component ( doc ).如果您想在兄弟组件之间共享数据,您应该始终牢记您应该将数据存储在最高公共组件( doc )中。

In your case that would mean having a parent component that holds your users list and the current profile in its state, and then render accordingly your list and the current profile.在您的情况下,这意味着有一个父组件在其 state 中保存您的用户列表和当前配置文件,然后相应地呈现您的列表和当前配置文件。

A little example to get you on the "right track" sandbox :一个让你走上“正确轨道”沙箱的小例子:

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

    this.state = {
      users: [],
      currentIndex: null
    }
  } 

  componentDidMount() {
      this.getUserList()
  }

  getUserList(){
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(result => result.json())
      .then(data => {
         this.setState(() => ({
           users : data
         }))
      });
    }

  updateCurrent = (index) => {
    this.setState(() => ({ currentIndex: index }));
  } 

  render() {
    return (
      <div>
        <UserList 
          users={this.state.users}
          updateCurrent={this.updateCurrent}
        />

        {this.state.currentIndex !== null && (
          <Profile user={this.state.users[this.state.currentIndex]} />
         )}
      </div>
    )
  }
}

const UserList = (props) => (
  <div>
    {props.users.map((user, i) => (          
      <div key={user.id}>
         <button color='primary' onClick={() => props.updateCurrent(i)}>View Profile</button>
      </div>
    ))}
  </div>
);

const Profile = ({ user }) => (
  <div className="profile-page">
    {user.name}     
  </div>
);

Feel free to ask clarification if needed.如果需要,请随时要求澄清。

Happy coding,快乐编码,

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

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