【问题标题】:From React to Vue, how to loop through an array with .map method?从 React 到 Vue,如何使用 .map 方法循环遍历数组?
【发布时间】:2020-10-31 04:51:57
【问题描述】:

我正在使用 vue 并且来自 react 背景。 React 有一个称为 .map 的方法,如果您将数组作为 props 传递,那么它将多次渲染该组件,具体取决于数组中的项目数并从索引中提取每个数据。像这样:

function App() {
const classes = useStyles();
const [finance, setFinance] = useState([]);

useEffect(() => {
    axios
        .all([
            axios.get(
                `https://cloud.iexapis.com/stable/stock/market/collection/list?collectionName=gainers&token=XXXXXXXXXXXXXXXXXXXXX`
            ),
        ])

        .then((res) => {
            setFinance(res[0].data);
        })
        .catch((err) => {
            console.log(err);
        });
}, []);

const cardList = finance.map((company, index) => (
    <Grid item xs={10} sm={5} md={4} lg={3} xl={2}>
        <Cards company={company} index={index} />
    </Grid>
));

基本上,finance 是存储数组中所有数据的状态。我将company 的数据作为道具传递给Cards 组件。这很有效,我正在尝试在 vue 中复制这种效果。到目前为止,这是我的代码:

<template>
  <v-container>
    <v-row align="start" justify="center">
      <v-col xs="12" sm="6" md="4" lg="3">
        <cards :crypto="crypto[0]" />
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import cards from "@/components/cards.vue";

export default {
  data() {
    return {
      crypto: []
    };
  },
  components: { cards },
  mounted() {
    this.axios
      .get(
        "https://min-api.cryptocompare.com/data/top/totalvolfull?limit=20&tsym=USD&api_key=xxxxxxxxxxxxxxxxxxx"
      )
      .then(response => {
        this.crypto = response.data.Data;
        console.log(response.data.Data);
      })
      .catch(error => console.log(error));
  }
};
</script>

如您所见,crypto 是我在 Vue 中的 cards 组件中传递的数据属性。我想做的与我对 React 所做的完全相同,而我将一个对象数组传递给一个组件,并且组件根据数组的对象数量多次渲染,同时从相应的获取数据指数。我尝试执行 v-for 指令,但我认为这只适用于列表?任何帮助表示赞赏。

注意: 这是我的 Vue 项目中用于上下文的 Card 组件:

<template>
  <v-card class="mx-auto" max-width="344" outlined>
    <v-list-item three-line>
      <v-list-item-content>
        <div class="overline mb-4">{{ crypto.CoinInfo.FullName }}</div>
        <v-list-item-title class="headline mb-1">{{
          crypto.CoinInfo.Name
        }}</v-list-item-title>
        <v-list-item-subtitle
          >Price: {{ crypto.DISPLAY.USD.PRICE }}<br />Change :
          {{ crypto.DISPLAY.USD.CHANGEDAY }}</v-list-item-subtitle
        >
      </v-list-item-content>

      <!-- <v-list-item-avatar tile size="80" -->
      <img
        style="height: 80px;"
        :src="`https://www.cryptocompare.com/${crypto.CoinInfo.ImageUrl}`"
      />
      <!-- </v-list-item-avatar> -->
    </v-list-item>

    <v-card-actions>
      <v-btn text>Save</v-btn>
      <v-btn text>Check</v-btn>
    </v-card-actions>
  </v-card>
</template>
<script>
export default {
  props: {
    crypto: Object
  }
};
</script>

【问题讨论】:

  • "React 有这个方法叫做 .map" - 没有。 finance 是一个普通数组值,它有 builtin map method。你可以在 vue.js 中完全一样地使用它。
  • 部分正确,使用渲染函数时只能在Vue的vdom中使用.map而不是&lt;template&gt;

标签: javascript arrays reactjs vue.js vuejs2


【解决方案1】:

查看v-for 指令:https://vuejs.org/v2/guide/list.html#Mapping-an-Array-to-Elements-with-v-for

尝试匹配您的 React 示例,您的案例将类似于:

<v-col v-for="(cryptoItem, index) in crypto" xs="11" sm="6" md="4" lg="3">
  <cards :crypto="cryptoItem" :index="index" />
</v-col>

【讨论】:

  • 我会看看这是否有效。人们提供的大多数示例只是使用列表而不是真正的组件。会试一试
  • 它说“迭代中的自定义元素需要'v-bind:key'
  • 啊,明白了。只需要 v-bind 键。
【解决方案2】:

使用 Vue CLI 生成的项目也可以使用 JSX in a render function,它可以让您执行类似于 React 解决方案的操作。这不一定是比使用 v-for“更好”的解决方案,但如果您更喜欢 JSX,它只是一个替代选项。

例如,容器组件可以获取数据,并将结果分配给绑定到CardList 组件的道具,该道具将道具映射到Card 组件的数组:

Container.vue

<template>
  <CardList :crypto="crypto" />
</template>

<script>
export default {
  async mounted() {
    const { data } = await axios.get(...)
    this.crypto = data
  }
}
</script>

CardList.vue

<script>
export default {
  props: {
    crypto: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  render() {
    return (
      <v-container>
        <v-row align="start" justify="center">
          <v-col xs="12" sm="6" md="4" lg="3">
            { this.crypto.map(crypto => <Card crypto={crypto} />) }
          </v-col>
        </v-row>
      </v-container>
    )
  },
};
</script>

demo

【讨论】:

  • 哇哦,真的吗?该死。我不知道。很棒的提示,以后肯定会使用它。
猜你喜欢
  • 2020-06-08
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 2019-12-10
  • 2021-03-11
  • 2021-11-07
  • 2019-09-04
  • 1970-01-01
相关资源
最近更新 更多