gpt4 book ai didi

javascript - React.js 不会在 setState 上重新渲染

转载 作者:行者123 更新时间:2023-12-03 03:36:47 25 4
gpt4 key购买 nike

我希望你能在这里提供帮助,因为我已经为此苦苦挣扎了一段时间,我正在尝试更改悬停时显示的图片,我从子组件调用的函数中获取新图片的 url ( passSingleImage),一旦我收到新的 url,我就会重置状态,我也会 console.logging 新状态,它确实在悬停时发生了变化,但是组件没有重新渲染!这是我的主要组件,其中状态已更改...

export default class ShowMore extends React.Component{
constructor(props){
super()
this.state = {
product: '',
photos:'',
currentImage: ''
}
}

componentDidMount(){
debugger
Tracker.autorun(()=>{
var product = Products.find({_id:this.props.location.query.id}).fetch()
var photos = Photos.find({id:this.props.location.query.id}).fetch()
if(photos.length > 0) {
this.setState({product,photos, currentImage:photos[0].url})
console.log("original state currentImage", this.state.currentImage)
}
})
}
passSingleImage(photo){
if(photo){
this.setState({currentImage:photo},( )=>{
console.log('set the state',this.state.currentImage)
this.forceUpdate()
this.render()
})

}
}

render(){
debugger
if(this.state.product.length > 0) {
return(
<div>
<TopBar/>
<div className ="container">
<div className="row">

<ul style = {{width: '30%'}} >
<li>name: {this.state.product[0].name}</li>
<li>price: {this.state.product[0].price}</li>
</ul>
<ImageSlider
photos = {this.state.photos}
history = {this.props.history}
passSingleImage = {this.passSingleImage}
/>
<BiggerImage
image = {this.state.currentImage}

/>
</div>
</div>
</div>


)
}else {
return <LoaderComp message ={'loading images'}/>
}
}
}

然后是显示图像的组件(始终相同!)

import React from 'react'
import TopBar from '../TopBar'

export default class BiggerImage extends React.Component{
constructor(props){
super()
}
componentWillReceiveProps(nextProp){
debugger
}
componentWillUpdate(a,b){
debugger
}
componentDidUpdate(a,b){
debugger
}
render(){
let img = {
maxWidth: '100%'
}
let abs = {
position:'absolute',
display:'inline-block',
width:'70%',
border:'1px solid black',
marginLeft:'4%',
marginRight:'4%'
}
return(
<div style = {abs}>

<div>
<img style = {img} src = {this.props.image} alt="image"/>
</div>
</div>
)
}

}

最佳答案

您正在丢弃 BiggerImage 的 props,而不是将它们传递给 super:

constructor(props) {
super() // sad trombone
}

要么删除构造函数(无论如何它都不做任何事情),要么更改它以传递 Prop :

constructor(props) {
super(props)
}

更多信息可以在React docs中找到.

关于javascript - React.js 不会在 setState 上重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45820971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com