循环更改组件状态

时间:2018-11-19 12:17:15

标签: javascript reactjs

我想像在this site上那样做动画菜单(我现在正在考虑导航栏下方的图像,这些图像会自行移动):

我有一个具有3个状态的组件,每个状态指示应显示带有链接的图像。我相信我应该使用setTimeout来更改组件的状态。我尝试使用componentDidMount / componentWillMount方法执行此操作,但收到错误消息:

  

TypeError:无法读取未定义的属性“为什么”

据我了解,这表明未设置状态?我在做什么错了?

export default class Menu extends Component {
  constructor(props) {
    super(props)
    this.state = {
      why: true,
      shop: false,
      workshop: false
    }
  }

  componentWillMount() {
    setInterval(function(){
      if (this.state.why) {
        this.setState({why: false, shop: true, workshop: false})
      }
      else if (this.state.shop) {
        this.setState({why: false, shop: false, workshop: true})
      }
      else if (this.state.workshop) {
        this.setState({why: true, shop: false, workshop: false})
      }
    }, 3000);
  }

  render() {
    return (
      <div>
        { this.state.why && 
          <a href='/'>
            <Image src={horizontal1}
              className='pics'
            />
          </a>
        }
        { this.state.shop && 
          <a href='/'>
            <Image src={horizontal2}
              className='pics'
            />
          </a>
        }
        { this.state.workshops && 
          <a href='/'>
            <Image src={horizontal3}
              className='pics'
            />
          </a>
        }
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

请使用粗箭头功能访问setInterval内部的构造函数

setInterval(()=> {
  if (this.state.why) {
    this.setState({why: false, shop: true, workshop: false})
  }
  if (this.state.shop) {
    this.setState({why: false, shop: false, workshop: true})
  }
  if (this.state.workshop) {
    this.setState({why: true, shop: false, workshop: false})
  }
}, 3000);