简体   繁体   English

React Child with useEffect() 不在 Parent 上更新 State Change

[英]React Child with useEffect() not updating on Parent State Change

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:我希望循环遍历一组对象以在 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.但是,子组件(画布)不会在父组件 state 更改时更新。

Add props.name to the useEffect dependency array so the function is called whenever props.name changes:props.name添加到useEffect依赖项数组,这样 function 就会在props.name更改时被调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM