简体   繁体   中英

reactjs - pass different props to the same component

Hello I have a challenge figuring out how I can extend and add extra props to the page. This below code snippet works just fine, and it populates basic text.

import React from 'react';
import { Text } from '@whatever-library';

const SomeComponent = (props) => (
  <div>
    <Text field={props.fields.heading} />
  </div>
);

So now I would like to add data from an external API to render in this same component. Below is a snippet from another .js file that is working and displaying content from the api fetch, how can I combine those two

    class apiFetch extends SomeComponent {
      constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoaded: false,
        }
      }

      componentDidMount() {
        fetch('')
        .then(res => res.json())
        .then(json => {
          console.log(json);
          this.setState({isLoaded: true, data: json.data});
        });

      }

        render() {
        var { isLoaded, data} = this.state;
        if (!isLoaded) {
          return <div>Loading...</div>;
        }

        else{
          return (
            <div className="apiFetch">
 <ul>
                {data.map(data => (
                  <li key="{data.id}">Text:{data.text.more}</li> 
                ))}
              </ul>
            </div>
          );
        }
      }

Any help or direction would be nice.

Is there a particular reason you're choosing to extend the component? For staters, the extends syntax is for JavaScript classes, but in your case you are trying to extend a function.

If your goal is to render data received from the API, there are a few ways to achieve this.

  1. You can make the request in a parent container component and pass the data to the child as a prop.

  2. You can use a higher order component (HOC) to pass additional props to the component. A HOC is a function that accepts a component as an argument and returns a new component. You can read more about HOCs here: https://reactjs.org/docs/higher-order-components.html

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