在Reaction组件上进行Map时,如何以及在何处调用函数以返回同一组件文件中的属性值?

zynd9foi  于 2022-10-15  发布在  React
关注(0)|答案(1)|浏览(124)

我目前使用的数据结构如下所示:

allPersons:[
    { discoveriesByType:[
        {type:'car',pending:0,confirmed:10, discoveries:[{data...}]},
        {type:'truck',pending:1,confirmed:25, discoveries:[{data...}]}
      ]
    },
    { discoveriesByType:[
        {type:'suv',pending:0,confirmed:10, discoveries:[{data...}]},
        {type:'atv',pending:1,confirmed:25, discoveries:[{data...}]}
      ]
    }
]

该数据结构在组件文件中表示为props.resultItemData,如下所示,并返回ResultItem组件。

<>
{ props.resultItemData.map((data, index) => {
      return(
        <ResultItem carOnlyPendingValue={this should be the value of discoveriesByType.type === 'cars' pending: its value} atvOnlyPendingValue={value} />
      )
  }
}
</>

在这个文件的什么地方,我应该创建一个函数来只获取pendingdiscoveriesByType.type === "suv"值?

gopyfrb3

gopyfrb31#

最简单的方法是计算值,并将其放在呈现函数之前的变量中。不需要useState或其他。请参阅工作演示:

function ResultItem({ carOnlyPendingValue, atvOnlyPendingValue }) {
  return <div style={{ border: '1px solid black' }}>
    ResultItem (Person):<br />
    <pre>carOnlyPendingValue: {carOnlyPendingValue} - atvOnlyPendingValue: {atvOnlyPendingValue}</pre>
  </div>;
}

function getPendingValueForType(discoveriesByType, type) {
  const discovery = discoveriesByType.find(d => d.type === type);
  return discovery ? discovery.pending : `<discovery '${type}' not found>`;
}

function MyComponent(props) {
  return (
    <div>
    { props.resultItemData.map((data, index) => {
        const carOnlyPendingValue = getPendingValueForType(data.discoveriesByType, 'car');
        const atvOnlyPendingValue = getPendingValueForType(data.discoveriesByType, 'atv');
        return(
          <ResultItem carOnlyPendingValue={carOnlyPendingValue} atvOnlyPendingValue={atvOnlyPendingValue} />
        );
      })
    }
    </div>
  );
}

function App() {
  const data = {
    allPersons:[
      { discoveriesByType:[
          {type:'car',pending:0,confirmed:10, discoveries:[{data: 'c'}]},
          {type:'truck',pending:1,confirmed:25, discoveries:[{data: 't'}]}
        ]
      },
      { discoveriesByType:[
          {type:'suv',pending:0,confirmed:10, discoveries:[{data: 's'}]},
          {type:'atv',pending:1,confirmed:25, discoveries:[{data: 'a'}]}
        ]
      }
    ]
  };
  return (
    <div><MyComponent resultItemData={data.allPersons} /></div>
  );
}

ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

如果不是简单的.find()进行复杂的计算,可以用useMemo() Package 它。

相关问题