如何解决将 props 传递给另一个组件并重绘页面
在 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
});
}
);
解决方法
将 fetch
分解为一个实用函数,当 props 更新时,可以在 componentDidMount
and 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
}
}
,
export default class Modal extends Component {
constructor(props){
super(props);
this.state = {
imgSrc: ' ',_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
});
}
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。