使用 useEffect() 反应子级未在父级状态更改时更新

Jim*_*ton 6 reactjs

在我的父组件中:

<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>
Run Code Online (Sandbox Code Playgroud)

我正在调用一个钩子:

handleOption = event => {
  event.preventDefault();
  let option = this.state.currentOption;
  const numOptions = this.state.stackOptions.length;
  if (++option >= numOptions) {
    option = 0;
  } 
  this.setState({
    currentOption: option,
  });
}
Run Code Online (Sandbox Code Playgroud)

我希望循环遍历对象数组以在 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}/>
}
Run Code Online (Sandbox Code Playgroud)

但是,子组件(画布)不会随着父状态更改而更新。

Ros*_*len 5

添加props.nameuseEffect依赖项数组中,以便每当更改时都会调用该函数props.name

  useEffect(() => {
    const canvas = canvasRef.current
    const context = canvas.getContext('2d')
    renderOption(props.name, canvas)
  }, [props.name])
Run Code Online (Sandbox Code Playgroud)