简体   繁体   中英

react load svg image from url

I am loading an svg image from a url passed in via the src prop.

The trouble I'm having is that I am storing the svg into state but when the url changes the image displayed will be the previous image clicked and not the current image

I can see that the image stored in state is always the last image selected

I believe it is how it is fetching the image from the api and storing it in to state here but I don't quite understand how this works and how it updates the state with the svg

).then(
   svg => this.state.image = svg
);

How can I change this so that state updates with the correct image?

SVG Component

import React from 'react';
import fetch from 'isomorphic-fetch';
import $ from 'jquery';

class InlineSVG extends React.Component {
  state = {
    image: '',
  };


  componentDidUpdate(prevProps) {
    this.loadSVG();
  }


  loadSVG() {
      fetch(this.props.src)
        .then(
          response => {
            if (!response.ok) return Promise.reject(new Error('Server 
Error'));
            return response.text();
          }
        ).then(
          svg => this.state.image = svg
        );
  }


  render() {
    return (
      <div>
      <div dangerouslySetInnerHTML={{__html: this.state.image}} />
      </div>
    );
  }
};

export default InlineSVG

Never mutate state directly. You are mutating state directly and that's why you don't see the Updated image. When you mutate the state directly your component won't re-render and that's why updated image isn't shown

Wrong

).then(
    svg => this.state.image = svg);

Right

 ).then(
    svg => this.setState({ image:  svg});

PS:- to modify React state value you need to use setState so that your component will re render with the updated data

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