React/JS 在过滤器中将两个数组连接在一起

React/JS Join two arrays together in a filter

反应

正如你在下面看到的,我有 5 个单词和 4 种颜色。在我的 CardList 中,我取前 4 个单词(随机给出)。然后我想给每个单词随机传递一种颜色。我有一个 shuffled_colors 数组来处理随机性。现在我只想要第 i 个卡片上的第 i 个颜色。当我传入 props.colors 时,它只是传入整个数组。我不确定如何去掉它的第 i 种颜色

App.js

const App = () => {
  var shuffleSeed = require('shuffle-seed');
  const words = ['One','Two', 'Three','Four','Five']
  const color= ['blue','blue','red','red']
  var shuffled_words = shuffleSeed.shuffle(words,"Kappa2");
  var shuffled_color = shuffleSeed.shuffle(color,"teams");

  console.log(shuffled_words)
  return (
    <div className="App">
      <h1>CodeNames</h1> 
      <CardList words={shuffled_words} colors={shuffled_color }/>
    </div>
  );
}

CardList.component

export const CardList = (props) => (
  <div className='card-list'>
    {props.words.filter((word, idx) => idx < 4)
      .map(word => (
        <Card key={word} word={word} color={props.colors}/>
      ))}
  </div>
)

首先在这里回答每个 React 问题。如果我还需要什么,请告诉我。

您需要使用props.colors[index]

Working demo

代码片段

export const CardList = props => (
  <div className="card-list">
    {props.words
      .filter((word, idx) => idx < 4)
      .map((word, index) => (
        <div key={word} word={word} color={props.colors[index]}>
          {word} '--' {props.colors[index]}
        </div>
      ))}
  </div>
);

export default function App() {
  var shuffleSeed = require("shuffle-seed");
  const words = ["One", "Two", "Three", "Four", "Five"];
  const color = ["blue", "blue", "red", "red"];
  var shuffled_words = shuffleSeed.shuffle(words, "Kappa2");
  var shuffled_color = shuffleSeed.shuffle(color, "teams");

  console.log(shuffled_words);
  return (
    <div className="App">
      <h1>CodeNames</h1>
      <CardList words={shuffled_words} colors={shuffled_color} />
    </div>
  );
}