相关疑难解决方法(0)

功能组件嵌套与 props

我对 React 还很陌生,我有一个关于架构和设计模式的问题。我已经完成了我的第一个项目(如果有人感兴趣的话,这是一个交互式图灵机排序器。我发现自己经常声明嵌套函数,例如

function MyReactList(props){
   const items = []
   for (let i=0; i<20;i++){
      function MyReactElem(props){
         return <div>
            <h1>{getHeadingFromSomewhereUsingIndex(i)}</h1>
            {getTextFromSomewhereUsingIndex(i)}
         </div>
      }
      
      items.push(<MyReactElement></MyReactElement>)

   }
   return items

}
Run Code Online (Sandbox Code Playgroud)

经过仔细检查,我意识到这可能完全没有意义,因为它 100% 相当于:

function MyReactList(props){
   
   function MyReactElem(props){
      return <div>
         <h1>{getHeadingFromSomewhereUsingIndex(props.index)}</h1>
         {getTextFromSomewhereUsingIndex(props.index)}
      </div>
   }

   const items = []
   for (let i=0; i<20;i++){
      items.push(<MyReactElement index={i}></MyReactElement>)
   }
   return items

}

Run Code Online (Sandbox Code Playgroud)

如果我没有记错的话,第二个版本应该使用更少的内存?我是否应该嵌套这样的功能组件?我的想法是在这样的范式下工作:每个限定符都应该从尽可能小的上下文中声明,但这也许是错误的,因为我不确定它还有什么其他含义,如果有人能给我一些提示,如果嵌套的功能组件是曾经是一个好主意,当情况确实如此时。

functional-programming inner-classes reactjs

4
推荐指数
1
解决办法
1085
查看次数