简体   繁体   中英

How to transfer data from one component to another in react?

There is a code that displays posts and by clicking on a post shows the full content of this post.

import React from "react";


type respX = {
    "id": any,
    "userId": any,
    "title": any,
    "body": any,
}

interface PropsI {
}

interface StateI {
    data: respX[];
    changedBody: string
    changedTitle: string
}

export class ComponentPostList extends React.Component<PropsI, StateI> {

    state: StateI = {data: [], changedBody: '', changedTitle: 'Click to choose article'}

    async getPostById(id: any) {
        const myResponse = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
        const myJson = await myResponse.json();
        this.setState({changedBody: myJson.body, changedTitle: myJson.title});
    }

    async componentDidMount() {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/`);
        const json = await response.json();
        this.setState({data: json});
    }


    render() {
        return (
            <div className="About">
                <div className="content">
                    <div className="title">{this.state.changedTitle}</div>
                    <div className="article">{this.state.changedBody}</div>
                </div>
                {this.state.data.map(el => (
                    <li onClick={e => this.getPostById(el.id)} key={el.id}>
                        {el.title}
                    </li>
                ))}
            </div>
        );
    }
}

How to transfer data from one component to another? To render the post headers in one component, and already the full content of the post in another component. These components are on the same level:

  <ComponentPostList data = {data} onClick = (getPostById) />
  <ComponentArticle post = {post} />

I prefer to use a callback function in this case. It's a simple way to solve your problem.

You have 2 components. You can pass a function to a child component to receive a value from a child component back to their parent.

class Parent extends React.Component {
  state = { post: null, data: null }

  async componentDidMount() {
    const data = await fetchData()
    this.setState({ data })
  }

  getPostById = async (id: any) => {
    const myResponse = await fetch(url);
    const post = await myResponse.json();
    this.setState({ post });
  }

  render() {
    <ComponentPostList 
      data={this.state.data} 
      postTitle={this.state.post.title} 
      changedBody={this.state.post.changedBody} 
      handleClick={this.getPostById}
    />
    <ComponentArticle postBody={this.state.post ? this.state.post.body : ''} />
  }
}

and your ComponentPostList should be like this...

class ComponentPostList extends React.Component {
    render() {
        return (
            <div className="About">
                <div className="content">
                    <div className="title">{this.props.postTitle}</div>
                    <div className="article">{this.props.changedBody}</div>
                </div>
                {this.props.data.map(el => (
                    <li onClick={e => this.props.handleClick(el.id)} key={el.id}>
                        {el.title}
                    </li>
                ))}
            </div>
        );
    }
}

On ComponentArticle , you use props to access value to render content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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