In my parent Component:
<div>
<h3>Option <span>{this.state.currentOption + 1}</span> of <span>{this.state.options}</span></h3>
<Button onClick={this.handleOption} variant="primary" type="submit">
{` Next >>`}
</Button>
</div>
I am calling a hook:
handleOption = event => {
event.preventDefault();
let option = this.state.currentOption;
const numOptions = this.state.stackOptions.length;
if (++option >= numOptions) {
option = 0;
}
this.setState({
currentOption: option,
});
}
Which I wish to cycle through an array of objects to render in Canvas:
import React, { useRef, useEffect } from 'react'
const StackRender = props => {
const canvasRef = useRef(null)
useEffect(() => {
const canvas = canvasRef.current
const context = canvas.getContext('2d')
renderOption(props.name, canvas)
}, [])
return <canvas ref={canvasRef} {...props}/>
}
however, the child component (the canvas) doesn't update on the parent state change.
Add props.name
to the useEffect
dependency array so the function is called whenever props.name
changes:
useEffect(() => {
const canvas = canvasRef.current
const context = canvas.getContext('2d')
renderOption(props.name, canvas)
}, [props.name])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.