简体   繁体   中英

React: How to get API data from one component and pass it to another

I am trying to pass data from my search bar component which returns a JSON from an API call to another component that will display the information. I am having a lot of trouble figuring it out. I tried making a container that holds both of the components and pass the data. Any help would be appreciated.

Thanks!

My Search Bar Component

class SearchBar extends Component {
constructor(props){
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e){
    e.preventDefault();
    let reqBody = {
      name: this.refs.name.value
    };
    fetch("/api", {
      method: "POST",
      body: JSON.stringify(reqBody),
      headers: {"Content-Type": "application/json"}
    })
      .then((res) => {
        if (res.ok){
          return res.json();
        } else {
          throw new Error ('Something went wrong');
        }
      }).then((json) => {
        console.log(json)
        this.props.onDataFetched(json)
      })
  }


  render() {
    return (
  <div >
    <form onSubmit={this.handleSubmit}>
    <input placeholder = "Enter Name" type="text" ref = "name"/>
    <button type ="Submit"> Search</button>

    </form>
  </div>
    );
  }
}

The component that displays the

class History extends Component {
    render() {
    return (
      <div >
        <h2> History</h2>


         <ul>
          <li>
          //display data here 

          </li>


         </ul>



      </div>
    );
  }
}

My container component

class Container extends Component {
    constructor(props){
        super(props);
        this.state ={
            history : []
        }
        this.handleResultChange = this.handleResultChange.bind(this)
    }
    handleResultChange(history){
        this.setState({
            history,
        })
    }

  render() {
    return (
      <div >
        <SearchBar onDataFetched={this.handleResultChange}/>
        <History data={this.state.history}/>
      </div>
    );
  }
}

我真的建议您看一下redux ,它将使您的开发更加轻松,并且几乎是这种情况下的标准实现。

You can handle the form submit in the search component in the itself. Pass the search value(input value) to the container component.

class SearchBar extends React.Component {
constructor(props){
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(e){
    e.preventDefault();
    let reqBody = {
      name: this.refs.name.value
    };

    console.log(reqBody);
    this.props.onDataFetched(reqBody);
}


  render() {
    return (
  <div >
    <form onSubmit={this.handleSubmit}>
    <input placeholder = "Enter Name" type="text" ref = "name"/>
    <button type ="Submit"> Search</button>

    </form>
  </div>
    );
  }
}

class Container extends React.Component {
    constructor(props){
        super(props);
        this.state ={
            history : []
        }
      this.handleChange = this.handleChange.bind(this)
    }

    handleChange(searchValue){
        console.log(searchValue);
    }

  render() {
    return (
      <div >
        <SearchBar onDataFetched={this.handleChange} />
      </div>
    );
  }
}
ReactDOM.render(<Container />, mountNode )

Now saying that the ideal way to do this would be as mentioned above by using redux and redux forms.

https://redux.js.org/

https://redux-form.com/

This will help you save a lot of time in the future as you will have a correct structure to do it.

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