最佳做法:仅准备一次道具进行渲染

问题描述

在nextjs应用程序中考虑以下简单页面

type MyProps = {
    myData: string[]
}

export const getServerSideProps: GetServerSideProps<MyProps> = async ({ req,res }) => {
    return { props: {myData: calcData()} }
}

function MyComponent(props: MyProps) {
   return <div>{props.myData}</div>
}

在道具中准备数据的最佳实践是什么?对于我来说,我需要根据服务器端代码(客户端浏览器中的当前语言)所不存在的标准对数据进行排序,使用next-i18next)。我可以使用像

这样的状态
function MyComponent(props: MyProps) {
   const [sortedProps] = useState({myData: props.myData.sort(...)})

   return <div>{sortedProps.myData}</div>
}

但这对我来说听起来并不像“ React想要的”。也许一次运行的useEffect(() => {...},[])是更好的选择?如果是,如何记起useEffect的结果数据? useRef

编辑:还是useMemo走的路?

解决方法

您可以按如下方式使用惰性初始状态:-

const [state,setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});


参考:https://reactjs.org/docs/hooks-reference.html#lazy-initial-state

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...