【问题标题】:Understanding unique key prop in React.js了解 React.js 中的唯一键道具
【发布时间】:2021-09-17 05:52:03
【问题描述】:

我正在构建一个 React 组件,它在订单摘要屏幕上显示数据以结束我的应用的订单流程。

我正在接收消息:

警告:列表中的每个孩子都应该有一个唯一的“key”属性。%s%s 请参阅...

这是完整的错误供参考:

Check the render method of `SummaryOrder`., , 
    in RCTView (at SummaryOrder.js:24)
    in SummaryOrder (at PreOrderScreen.js:111)
    in ScrollView (at PreOrderScreen.js:105)
    in RCTView (at PreOrderScreen.js:99)

错误位置也标有“=>”。

SummaryOrder.js:

import React from "react";
import { View, StyleSheet } from "react-native";
//Number
import NumberFormat from "../../../components/UI/NumberFormat";
//PreOrderItem
import PreOrderItem from "./PreOrderItem";
//Text
import CustomText from "../../../components/UI/CustomText";
import Colors from "../../../utils/Colors";
//PropTypes check
import PropTypes from "prop-types";

export class SummaryOrder extends React.PureComponent {
  render() {
    const { cartItems, total } = this.props;
    return (

    in RCTView (at SummaryOrder.js:24) =>  ***<View style={styles.container}>***


        <CustomText style={{ ...styles.title, marginVertical: 5 }}>
        Order Summary
        </CustomText>
        <View style={{ backgroundColor: "#fff", paddingHorizontal: 10 }}>
          {cartItems.map((item) => {
            return (


     in SummaryOrder (at PreOrderScreen.js:111)  =>  ****<View key={item.item.createdAt}>****


                <PreOrderItem item={item} />
              </View>
            );
          })}
        </View>
        <View style={styles.total}>
          <CustomText
            style={{
              fontSize: 15,
              color: Colors.text,
              fontWeight: "500",
            }}
          >
            Total
          </CustomText>
          <NumberFormat price={total.toString()} />
        </View>
      </View>
    );
  }
}

SummaryOrder.propTypes = {
  cartItems: PropTypes.array.isRequired,
  total: PropTypes.number.isRequired,
};

PreOrderScreen.js:

import React, { useState, useEffect, useRef } from "react";
import { useIsFocused } from "@react-navigation/native";
import { View, StyleSheet, ScrollView } from "react-native";
//Address
import Address from "./components/Address";
//Redux
import { useSelector } from "react-redux";
//Steps
import Colors from "../../utils/Colors";
import { Header, SummaryOrder, TotalButton, UserForm } from "./components";
import Loader from "../../components/Loaders/Loader";

export const PreOrderScreen = (props) => {
  const unmounted = useRef(false);
  const isFocused = useIsFocused();
  const [loading, setLoading] = useState(true);
  const carts = useSelector((state) => state.cart.cartItems);
  const { cartItems, total, cartId } = props.route.params;
  const [error, setError] = useState("");
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [province, setProvince] = useState("");
  const [town, setTown] = useState("");
  useEffect(() => {
    return () => {
      unmounted.current = true;
    };
  }, []);
  useEffect(() => {
    if (isFocused) {
      setLoading(true);
      const interval = setInterval(() => {
        setLoading(false);
      }, 1000);
      return () => clearInterval(interval);
    }
    return;
  }, [isFocused]);
  const getInfo = (province, town) => {
    setProvince(province);
    setTown(town);
  };
  const getReceiver = (name, phone, address) => {
    setName(name);
    setPhone(phone);
    setAddress(address);
  };
  const checkValidation = (error) => {
    setError(error);
  };
  let orderItems = [];
  cartItems.map((item) => {
    orderItems.push({ item: item.item._id, quantity: item.quantity });
  });

  const fullAddress = `${address}, ${town} ,${province}`;
  const toPayment = async () => {
    try {
      if (error == undefined && province.length !== 0 && town.length !== 0) {
        props.navigation.navigate("Payment", {
          screen: "PaymentScreen",
          params: {
            fullAddress,
            orderItems,
            name,
            phone,
            total,
            cartId,
            carts,
          },
        });
      } else {
        alert("Please enter your full information.");
      }
    } catch (err) {
      throw err;
    }
    props.navigation.navigate("Payment", {
      screen: "PaymentScreen",
      params: {
        fullAddress,
        orderItems,
        name,
        phone,
        total,
        cartId,
        carts,
      },
    });
  };
  useEffect(() => {
    if (carts.items.length === 0) {
      props.navigation.goBack();
    }
  }, [carts.items]);
  return (

  in RCTView (at PreOrderScreen.js:99) =>  ***<View style={styles.container}>***

      <Header navigation={props.navigation} />
      {loading ? (
        <Loader />
      ) : (
        <>
          <ScrollView>
            <UserForm
              getReceiver={getReceiver}
              checkValidation={checkValidation}
            />
            <Address getInfo={getInfo} />

      in ScrollView (at PreOrderScreen.js:105) =>
    ***<SummaryOrder cartItems={cartItems} total={total} />***


          </ScrollView>
          <TotalButton toPayment={toPayment} />
        </>
      )}
    </View>
  );
};

提前感谢您的帮助!

【问题讨论】:

  • 您能告诉我们cartItems 中的内容吗? createdAt 值对它们来说不是唯一的。快速解决方法是使用索引,但如果您打算进行任何删除或排序,您应该为项目使用某种唯一标识符(电子邮件、用户 ID 等)。

标签: javascript reactjs react-native


【解决方案1】:

createdAt 值对它们来说不是唯一的。快速解决方法是改用index,但如果您打算进行任何删除或排序,您应该为项目使用某种唯一标识符(电话、电子邮件、用户 ID 等)。我只浏览了您的代码,但您可以使用电话代替。

键很重要,因为它会在需要更新列表时提示 React。文档对https://reactjs.org/docs/lists-and-keys.html#keys 很有帮助,了解更多信息。

无论如何,这里显示了快速修复。阅读https://stackoverflow.com/a/43642421 了解为什么不应该这样做。我会把更好的实现留给你。

...
{ cartItems.map((item, index) => {
    return (
        <View key={index}>
            <PreOrderItem item={item} />
        </View> );
    }) 
}
...

【讨论】:

    【解决方案2】:

    当你在 react 中使用 map 时,你应该为重复的标签或组件定义一个唯一的 key,这是为了 react 跟踪你正在映射的 array 的变化,如果array、react 中发生的任何更改都会知道在哪里重新渲染相关的 tag 或 component,而不要管其他人 :)

    如果您没有重新排序数组的计划,您可以简单地将index 用作key,但是如果您想重新排序数组元素,最好先定义一个唯一的 id为他们(如果它不是由服务器提供)然后做map数组

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2020-11-15
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      相关资源
      最近更新 更多