简体   繁体   中英

React load page with fetch

I'm trying to show content of my url /PaisForm inside of div but doenst work. My code is this:

componentDidMount(){
    fetch('/PaisForm')
    .then(function(response) {
        return response.text();
    })
    .then(function(body) {
        document.querySelector('.Pais').innerHTML = body;
    });
}

and this is my div:

render() {
     return(

       <div className= "Pais">
       </div>
      );
    }
}

When i use console.log in function(body) i can read this:

You need to enable JavaScript to run this app.

  You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. 

Thanks for any help, i dont know if i'm using bad the fetch.

You need to enable JavaScript to run this app.

This means your browser is not allowed to run any Javascript .

To unable Javascript on Chrome you can do this (If you are using another browser then do serach on Google how to unable Javascript on that particular browser).


Another thing is, don't directly manipulate the DOM like,

document.querySelector('.Pais').innerHTML = body;

Instead you can have a variable in state,

state={body:''}

And you can make use of setState ,

componentDidMount(){
    fetch('/PaisForm')
    .then(function(response) {
      return response.text();
    })
    .then(function(body) {
      this.setState({body});
    });
  }

And you can render data from state,

<div className= "Pais">
    {this.state.body}
</div>

Update

It seems to be you'r trying to add a component in another component using fetch .

FYI fetch is only meant for API calling.

To actually add a component you need to import that component.

import PaisForm from "./file_path";

and simply add that component wherever you want,

<div className= "Pais">
    <PaisForm />
</div>

The way to include another component in your react component is like this

First n top of the component

import PaisForm from './PaisForm' //path to file

Then in the component

// your code
<div>
    // use your component
    <PaisForm />
</div>

Also make sure you have in your PaisForm component

export default PaisForm

Hope this helps.

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