2

这是我的反应钩子代码:

function Simple(){
    var [st,set_st]=React.useState(0)
    var el=React.useRef(null)
    if (st<1)
        set_st(st+1)//to force an extra render for a grand total of 2
    console.log('el.current',el.current,'st',st)
    return <div ref={el}>simple</div>
}
ReactDOM.render(<Simple />,document.querySelector('#root') );

我认为它应该渲染两次。第一次 el.current 应该为空,第二次应该指向 div 的 DOM 对象。运行时,这是输出

el.current null st 0
el.current null st 1

是的,它确实渲染了两次。但是,第二次渲染 el.current 仍然为空。为什么?

解决方案:如下 Gireesh Kudipudi 所述。我添加了 useEffect

function Simple(){
    var [st,set_st]=React.useState(0)
    var el=React.useRef(null)
    if (st<1)
        set_st(st+1)//to force an extra render for a grand total of 2
    console.log('el.current',el.current,'st',st)
    React.useEffect(_=>console.log('el.current',el.current,'st',st)) //this prints out the el.current correctly
    return <div ref={el}>simple</div>
}
ReactDOM.render(<Simple />,document.querySelector('#root') );
4

2 回答 2

4

可能是你专注于渲染的数量,这不一定是使用钩子时最好的 React 思维方式。心态应该更像是我的世界发生了什么变化

从那时起,尝试添加一个useEffect并告诉它您有兴趣查看ref我的世界何时发生变化。试试下面的例子,自己看看行为。

let renderCounter = 0;

function Simple() {
  const [state, setState] = useState()
  const ref = React.useRef(null)

  if (state < 1) {
    /** 
     * We know this alter the state, so a re-render will happen
     */
    setState('foo')
  }

  useEffect(() => {
    /**
     * We don't know exactly when is `ref.current` going to
     * point to a DOM element. But we're interested in logging
     * when it happens.
     */
    if (ref.current) {
      console.log(ref.current)

      /**
       * Try commenting and uncommenting the next line, and see
       * the amount of renderings
       */
       setState('bar');
    }

  }, [ref]);

  renderCounter = renderCounter + 1
  console.log(renderCounter);

  return <div ref={el}>simple</div>
}

React 将在使用值初始化时重新渲染ref,但这并不意味着它会在第二次渲染时发生。

要回答您的问题,您还没有告诉 react 在更改时要做什么ref

于 2020-08-07T22:42:42.607 回答
0
class SimpleComponent extends React.Component{
  el = React.createRef(null)
  constructor(props){
    super(props)
    this.state = {
      st:0
    }
  }
  componentDidMount(){
    if(this.state.st<1)
      this.setState(prevState=>{
        return {st:prevState.st+1}
      })
  }

  render(){
    console.log('el.current',this.el.current,'st',this.state.st)
    return <div ref={this.el}>simple</div>
  }
}

ReactDOM.render(<SimpleComponent />,document.querySelector('#root') );

输出是

el.current null st 0
el.current <div>​simple​&lt;/div>​ st 1

根据文档

ReactDOM.render(元素,容器[,回调])

在提供的容器中将 React 元素渲染到 DOM 中,并返回对组件的引用(或为无状态组件返回 null)。

由于您尝试引用功能组件,因此可能是原因。由于您的问题,我遇到了有趣的场景。

此外,如果用作子组件,则输出符合预期

于 2020-08-07T22:26:35.267 回答