简体   繁体   中英

How to use dynamic url in nextjs

I am working with nextjs,I am fetching image(via api),Right now i am getting "Full image path"(for example,"https//myurl.com/image/imagename.jpg") so i am fetching without any problem,but i want to know that if i have only "image name"(for example,"imagename.jpg") so how can we fetch in front end ? in other words how can i pass "url/hostname" before imagename ? Should i create seprate "component" and mention "host url" and fetch whereever i want OR Should i create "variable" like following code or is there another way ?

class Company extends React.Component {
    const orig = 'http://anyurl.com';

    state = {
        trending: []
      }
    componentDidMount() {
        axios.get('https://myurl.com/apipath',
        )
          .then(res => {
            const trending = res.data;
            this.setState({ trending });
          })
      }

    render() {
            return 
                (

                    <img src={post.image} /> 
                );      
            );
        }

If you know the base URL, you can use Template Literals for the same. For Example:

const orig = 'https://myurl.com/apipath';
const imageName = 'image1.jpg';
const imgUrl = `${orig}/${imageName}`

Make a separate Variable and add them like this ${} in string literal. then you will use dynamic fetching.

You can create a variable baseURL that contains a constant path to your backend URL. This would be static. The only dynamic part is your imageFileName. You can store this in state or get it from props or where ever you are getting the imagename.jpg from.

When you want to define some constant values like style or image URLs then it's always better to define that outside of component. It will become global values and available inside each function/class of that file.

config/urlConfig.js

export const urlConfig={
    baseURL: 'http://myurl.com/image/'
}

//Your component

import { urlConfig } from 'path/to/your/config/urlConfig';
class Company extends React.Component {
    state = {
        trending: [],
        imageFileName: 'imagename.jpg'   // Assign any value to this
      }
    componentDidMount() {
        axios.get(urlConfig.baseURL + this.state.imageFileName,
        )
          .then(res => {
            const trending = res.data;
            this.setState({ trending });
          })
      }

    render() {
            return 
                (

                    <img src={post.image} /> 
                );      
            );
        }

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