1. Introduction to the problem
1. I encountered such a problem when writing a react project today (look at the code first):
import React, {
Component } from 'react'
import {
Link } from 'react-router-dom'
import './index.css'
export default class CarouselMap extends Component {
state = {
index:0,
carouselMaps:[
{
//图片src
imgSrc:'/images/图层 1.png',
//去哪里?
to:''
},
{
//图片src
imgSrc:'/images/云朵穿心.jpg',
//去哪里?
to:''
},{
//图片src
imgSrc:'/images/可爱兔子.jpg',
//去哪里?
to:''
},
{
//图片src
imgSrc:'/images/风景 1.jpg',
//去哪里?
to:''
}
]
}
componentDidMount(){
const {
carouselMaps} = this.state
let num = 0
this.srcTimer = setInterval(()=>{
if(num+1===carouselMaps.length)
num=0
else
num++
this.setState({
index:num})
},3000)
}
componentWillUnmount(){
clearInterval(this.srcTimer)
}
render() {
const {
index,carouselMaps} = this.state
return (
<div id='carouselMap'>
<ul>
<li>
<Link>
<img src={
carouselMaps[index].imgSrc} alt="" />
</Link>
</li>
</ul>
{
/* 这个div不显示 */}
<div>aaaaa</div>
</div>
)
}
}
I want that picture to change every 3 seconds, and it does happen. But something went wrong with the div I added later.
The div appears on the page, but its content and background color are not displayed. I can display it by removing the previous image that changes over time.
I couldn't find this problem online, but I found a solution
1. Problem solving
We just need to advance the position of the div:
<div>aaaaa</div>
<ul>
<li>
<Link>
<img src={
carouselMaps[index].imgSrc} alt="" />
</Link>
</li>
</ul>
Or use a middleware:
import React, {
Component } from 'react'
import CarouselMap from '../CarouselMap'
import Test from '../Test'
export default class Test1 extends Component {
render() {
return (
<div>
<CarouselMap/>
{
/* Test里面放后面的东西,如:刚刚的div */}
<Test/>
</div>
)
}
}
Finally, if you want to know why this problem occurs, you can let us know in the comment area. Let’s learn together