简体   繁体   中英

Pass props to another component and redraw the page

In 1 component, when I click on the picture, I get its id, which I pass to another component via props. I need to receive these props every time and send a feth - request with the id of the image and then redraw the component. How to do it correctly?

first component

export default class Home extends Component {
constructor(props) {
    super(props);
    this.state = {
        error: null,
        isLoaded: false,
        isOpen: false,
        images: [],
        idImg: ''
    };

}
 openModal = (e) => {
    this.setState({ isOpen: true, idImg: e.target.id });
  }
render() {
    const {error, isLoaded, images} = this.state;

    if (error) {
        return <p>Error</p>
    } else if (!isLoaded) {
        return <p> Loading ... </p>
    } else {
        return (
            <div className="row align-items-center m-4" onChange={this.onSelect}>
                <Modal
                    isOpen={this.state.isOpen}
                    onCancel={this.handleCancel}
                    onSubmit={this.handleSubmit}
                    idImg={this.state.idImg}
                ></Modal>
                {images.map(item => (
                    <div key={item.image_id} className="col-lg-4 col-lg-4 sm-1 p-2" style={{Style}}  >
                        <img id={item.image_id} src={item.src} alt={item.src} onClick={this.openModal}></img>
                    </div>
                ))}
            </div>
        )
    }
}

2 component:

export default class Modal extends Component {
constructor(props){
    super(props);
    this.state = {
        imgSrc: ' ',
        commentList: [], 
        _id: this.props.idImg
    }
}


componentDidMount(){
    fetch(`./api/${this.state._id}`, {
        method: 'GET',
        })
    .then(res => res.json())
    .then((result) => {
        this.setState({
            isLoaded: true,
            imgSrc: result.src
        });
    },
    (error) => {
        this.setState({
            isLoaded: true,
            error
        });
    }
    );

Factor out the fetch into a utility function that can be called in componentDidMount and componentDidUpdate when the props update.

Also, don't store passed props into local component state, this is an anti-pattern in react. You can simply consume the passed idImg prop in the lifecycle methods.

export default class Modal extends Component {
  constructor(props){
    super(props);
    this.state = {
      imgSrc: ' ',
      commentList: [], 
    }
  }

  fetchImage = imageId => {
    this.setState({ isLoaded: false }); // <-- set loading state
    fetch(`./api/${imageId}`, {
        method: 'GET',
        })
      .then(res => res.json())
      .then((result) => {
        this.setState({
          isLoaded: true,
          imgSrc: result.src
        });
      },
      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    );
  };

  componentDidMount() {
    this.fetchImage(this.props.idImg); // <-- pass idImg prop
  }

  componentDidUpdate(prevProps) {
    if (prevProps.idImg !== this.props.idImg) { // <-- compare idImg values
      this.fetchImage(this.props.idImg); // <-- pass idImg prop
    }
  }
 export default class Modal extends Component {
    constructor(props){
        super(props);
        this.state = {
            imgSrc: ' ',
            commentList: [], 
            _id: this.props.idImg
        }
this.nameFunction=this.nameFunction.bind(this);
    }
    
    
    componentDidMount(){
this.nameFunction();
        }
    componentDidUpdate(prevProps) {
        if (prevProps.idImg!== this.props.idImg) {
            this.setState({
                _id: this.props.idImg,
            })
        }
    }
nameFunction(){
fetch(`./api/${this.state._id}`, {
            method: 'GET',
            })
        .then(res => res.json())
        .then((result) => {
            this.setState({
                isLoaded: true,
                imgSrc: result.src
            });
        },
        (error) => {
            this.setState({
                isLoaded: true,
                error
            });
        }
        );
}

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