将 props 传递给另一个组件并重绘页面

Pass props to another component and redraw the page

在 1 个组件中,当我点击图片时,我得到它的 id,我通过 props 将它传递给另一个组件。我每次都需要接收这些道具并发送一个带有图像 ID 的 feth - 请求,然后重绘组件。如何正确操作?

第一部分

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 个分量:

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
        });
    }
    );
 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
            });
        }
        );
}

fetch 分解为可以在 componentDidMount 中调用的效用函数 componentDidUpdate道具更新时

此外,不要将传递的 props 存储到本地组件状态中,这是 React 中的反模式。您可以简单地在生命周期方法中使用传递的 idImg 道具。

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
    }
  }