使用useEffect()对子级做出反应,而不是根据父级状态更新

时间:2020-09-20 22:22:45

标签: 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>

我正在呼叫一个钩子:

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

我希望循环浏览一系列对象以在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}/>
}

但是,子组件(画布)不会在父状态更改时更新。

1 个答案:

答案 0 :(得分:3)

props.name添加到useEffect依赖项数组中,以便在props.name发生更改时调用该函数:

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