【问题标题】:REACT wait for useEffect to complete before rendering the UIREACT 在渲染 UI 之前等待 useEffect 完成
【发布时间】:2021-11-21 20:44:24
【问题描述】:
interface MyValue {
    //interface declaration
}
    
export function MyComponent {   
    const [myvalue, setMyvalue] = useState<MyValue>()
    
    useEffect(() => {
       setMyvalue(passedData)
    }, [passedData])
    
    function getAutofocus() {
        // return true/false based on myvalue value
    }
        
    render() {
       return (
          <div>
             <input
                autofocus={getAutofocus()}
                ref={c => (this._input = c)}
             />
          </div>
         );
       }
    }
 }

passedData 作为 prop 从 parent 传递,并通过服务器 GET 调用填充到 parent,这需要一些时间来解决。

问题 - getAutofocus() 在正确加载 passedData 之前呈现。

我的要求是等到passedData被正确解析后再调用 getAutofocus() 方法。 如果我们可以在 passedData 完全解析之前停止 UI/ 或输入字段的呈现,这将允许 getAutofocus() 正确执行。

最好的方法是什么?这里可以用react suspence吗?

【问题讨论】:

  • 附带问题。是否可以像在类 React 组件类中那样使用钩子(useState、useEffect)?也就是说,我认为钩子仅适用于单一功能(“纯”)组件。
  • 将代码更改为使用函数而不是类
  • 这仍然不是您实现纯组件的方式。取出render() 声明,最后的声明就是 JSX 元素的返回。

标签: reactjs typescript react-hooks use-effect react-component


【解决方案1】:

听起来像条件​​渲染就足以满足您的需求:

    render() {
       // if myvalue is not populated yet, do not render anything
       return !myvalue ? null : (
          <div>
             <input
                autofocus={getAutofocus()}
                ref={c => (this._input = c)}
             />
          </div>
         );
       }
    }

【讨论】:

    【解决方案2】:

    这样做的正确方法是使用参考

    const MyCom = props => {
    
    const inputRef = React.useRef();
    
    React.useEffect(()=>{
      if (inputRef.current) {
         inputRef.current.focus();
    }
    
    },[inputRef]);
    
    return (
              <div>
                 <input
                    ref={inputRef}
                 />
              </div>
             );
    }
    

    移除渲染方法只有类组件有渲染

    【讨论】:

      猜你喜欢
      • 2022-12-14
      • 2021-05-18
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多