-1

有一个组件接收道具。

props 有一个数组的形状,对于这个数组的每个元素,一个函数将返回一个不同的组件来渲染。

function MainComponent ({ data }) => { // data is props, an array

  const specialFunction = (index) => {
    switch (index) {
    case 0:
      return <Component0 />;
    case 1:
      return <Component1 />;
    case 2:
      return <Component2 />;
    default:
      return null;
    }
  };
  ...
  return (
     ...
     data.map((item, index) => {
        ... // do other stuff with item
        <div>{specialFunction(index)}</div> // the function that we talk about
   
     ...
  );

如果道具不会改变,有没有办法记住这个结果?或者有什么更好的写法?

4

3 回答 3

-1

带有空依赖数组的useCallback将是这里的最佳方法。useCallback 将返回回调的记忆版本,仅当其中一个依赖项发生更改时才会更改。由于我们的依赖数组是[],它只会被初始化一次,并且返回的 memonized 函数将在后续函数调用中使用。

const specialFunction = useCallback((index) => {
    switch (index) {
    case 0:
      return <Component0 />;
    case 1:
      return <Component1 />;
    case 2:
      return <Component2 />;
    default:
      return null;
    }
  }, []);
于 2021-11-11T12:41:03.983 回答
-1

其他模式,我认为在这种情况下最优雅的是使用:

const components = {
   0: <Component0 />,
   1: <Component1 />,
   2: <Component2 />,
}

/*
or
const components = [<Component0 />, <Component1 />, <Component2 />]
*/

function MainComponent ({ data }) => {
  ...
  return (
     ...
     data.map((item, index) => 
        <div>{components[index] || null}</div>
     ...
  );

于 2021-11-11T13:33:26.713 回答
-1

有几种方法可以实现这一点:

  1. 您可以使用状态来存储数组

const [components] = useState([<Component0 />, <Component1 />, <Component2 />])

然后components[index]在尝试渲染时使用。

  1. 您可以尝试记住useCallback您的功能。
于 2021-11-11T12:34:25.823 回答