Im new to React and have some trouble right now.
I have component, which catches some object as props and few functions to change state once at few seconds:
export default class Header extends React.Component {
constructor(props) {
super(props)
this.state = {
variants: props.variants,
background: props.variants[0].background
}
}
setTimer () {
const { variants } = this.state
clearTimeout(this.timeout)
this.timeout = setTimeout(this.updateBackground.bind(this), 1000)
}
updateBackground () {
console.log(`Keys ${this.state.variants}`);
const { variants } = this.state
const { background } = variants[parseInt(Math.random() * 5)]
setState({
background: background
}, this.setTimer)
}
componentDidMount() {
this.setTimer()
}
render() {
const { background } = this.state
return (
<div className="header-image"> <img src={ background } /> </div>
)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
My problem is: after
this.updateBackground.bind(this)
call, updateBackground lost all state values, e.g.
this.state.variants
is defined, but its no more contains objects, e.g
this.state.variants[0] === undefined
Explain to me please what i doing wrong :)
this.setStatevariantsin state, you can just use the value from props directly. You should avoid putting props into initial state, and if you do, prefix the props with 'initial' - like "initialVariants": see medium.com/@justintulk/…<Header variants={['abc.jpg', ...]} />? That should help people rule out the props not being passed in correctly.