node.js - 警告 : Each child in a list should have a unique "key" prop. %s%s

标签 node.js mongodb react-native mongoose

向整个社区问好。

我正在做一个项目,我所在城市的餐馆可以通过应用程序放置菜肴并生成订单。

但是我的项目在执行时出现错误。

这是我犯的错误。

Warning: Each child in a list should have a unique "key" prop.%s%s  
Check the render method of `VirtualizedList`., , 
    in CellRenderer (at VirtualizedList.js:767)
    in VirtualizedList (at FlatList.js:676)
    in FlatList (at Meals.tsx:14)
    in RCTView (at Meals.tsx:12)
    in Meals (at SceneView.js:9)
    in SceneView (at StackViewLayout.tsx:900)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewCard.tsx:106)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at screens.native.js:100)
    in Screen (at StackViewCard.tsx:93)
    in Card (at createPointerEventsContainer.tsx:95)
    in Container (at StackViewLayout.tsx:975)
    in RCTView (at screens.native.js:131)
    in ScreenContainer (at StackViewLayout.tsx:384)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewLayout.tsx:374)
    in PanGestureHandler (at StackViewLayout.tsx:367)
    in StackViewLayout (at withOrientation.js:30)
    in withOrientation (at StackView.tsx:104)
    in RCTView (at Transitioner.tsx:267)
    in Transitioner (at StackView.tsx:41)
    in StackView (at createNavigator.js:80)
    in Navigator (at createKeyboardAwareNavigator.js:12)
    in KeyboardAwareNavigator (at SceneView.js:9)
    in SceneView (at StackViewLayout.tsx:900)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewCard.tsx:106)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at screens.native.js:100)
    in Screen (at StackViewCard.tsx:93)
    in Card (at createPointerEventsContainer.tsx:95)
    in Container (at StackViewLayout.tsx:975)
    in RCTView (at screens.native.js:131)
    in ScreenContainer (at StackViewLayout.tsx:384)
    in RCTView (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewLayout.tsx:374)
    in PanGestureHandler (at StackViewLayout.tsx:367)
    in StackViewLayout (at withOrientation.js:30)
    in withOrientation (at StackView.tsx:104)
    in RCTView (at Transitioner.tsx:267)
    in Transitioner (at StackView.tsx:41)
    in StackView (at createNavigator.js:80)
    in Navigator (at createKeyboardAwareNavigator.js:12)
    in KeyboardAwareNavigator (at createAppContainer.js:430)
    in NavigationContainer (at withExpoRoot.js:26)
    in RootErrorBoundary (at withExpoRoot.js:25)
    in ExpoRoot (at renderApplication.js:40)
    in RCTView (at AppContainer.js:101)
    in DevAppContainer (at AppContainer.js:115)
    in RCTView (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:39)

我正在我的前端使用 React-native 做这个项目。

**我的代码是这样的 - 我的前端**

App.js

import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import MealsScreen from './src/screens/Meals';
import Modal from './src/screens/Modal';

const AppNavigation = createStackNavigator({
  Meals: {
    screen: MealsScreen
  }
}, {
  initialRouteName: 'Meals'
});

const RootStack = createStackNavigator( {
  Main: AppNavigation,
  Modal: Modal,
}, {
  mode: 'modal',
  headerMode: 'none',
});

export default createAppContainer( RootStack );

膳食

import React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import ListItem from '../components/ListItem';
import UseFetch from '../hooks/useFetch';

const Meals = ({navigation}) => {
    const { loading, data: meals } = UseFetch('https://serverless.mgyavega.now.sh/api/meals');

    return(
        <View style =  { styles.container }>
            { loading ? <Text style =  { styles.text }>Cargando por favor espere...</Text> :
                <FlatList
                    style = { styles.list }
                    data = { meals }
                    keyExtractor= { x => x.id }
                    renderItem = {({ item }) =>
                        <ListItem
                            onPress={ () => navigation.navigate('Modal', { id: item.id })}
                            name = { item.name }
                        />
                    }
                />
            }
        </View>
    )
}

Meals.navigationOptions = ({
    title: 'Comidas Disponibles',
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'flex-start',
        justifyContent: 'flex-start'
    },
    list: {
        alignSelf: 'stretch'
    },
    text: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    }
});

export default Meals;

创建一个调用 Flatlist 操作的列表并管理列表上的信息。

List.js

import React from 'react';
import {  TouchableOpacity, Text, StyleSheet } from 'react-native';

export default ({ name, onPress }) => {
    return (
        <TouchableOpacity onPress = { onPress } style={ styles.container }>
            <Text style = { styles.text }> {name} </Text>
        </TouchableOpacity>
    )
}

const styles = StyleSheet.create({
    container: {
        paddingHorizontal: 15,
        height: 60,
        justifyContent: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#eee'
    },
    text: {
        fontSize: 16
    }
});

获取我的项目的 url。

UseFecth.js

import { useEffect, useState } from 'react';

const UseFetch = ( url ) => {
    const [loading, setLoading] = useState(true);

    const [ data, setData] = useState([]);

    const fetchData = async () => {

        const response = await fetch(url);

        const data  = await response.json();

        setData(data);

        setLoading(false);
    };

    useEffect(() => {
        fetchData();
    }, [] );

    return { loading, data }
}

export default UseFetch;

我的 modal.js

import React from 'react';
import {  View, Text, } from 'react-native';
import UseFetch from '../hooks/useFetch';

export default ({navigation}) => {

    const id = navigation.getParam('_id');
    const { loading, data } = UseFetch(`https://serverless.mgyavega.now.sh/api/meals/${id}`);

    console.log( 'Información del id del menú: ', id );

    return (

        loading ? <Text>Cargando </Text> :
            <View>
                <Text>  </Text>
                <Text>  </Text>
            </View>

    )
}

我正在使用 MongoDB、Ziet 和 Node.js 做后端。

这是我的路线。

index.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());
var meals = require('./routes/meals');
var orders = require('./routes/orders');

mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true } );

app.use('/api/meals', meals);
app.use('/api/orders', orders);

module.exports = app;

Meals.js

var express = require('express');
var Meals = require('../models/meals');
var router = express.Router();

router.get('/', ( req, res ) => {
    Meals.find()
         .exec()
         .then( x => {
             res.status(200).send(x)
    });
});

router.get('/:id', ( req, res ) => {
    Meals.findById(req.params.id)
         .exec()
         .then( x => {
             res.status(200).send(x);
    });
});

Models.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const Meal = mongoose.model('Meal', new Schema({
    name: String,
    desc: String,
}));

module.exports = Meal;

我不知道为什么这些信息与我重复。

感谢您给予我的合作。

谢谢。

马里奥

最佳答案

我最好的猜测是该行正在生成重复的 key 。

keyExtractor= { x => x.id }

关于node.js - 警告 : Each child in a list should have a unique "key" prop. %s%s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59381995/

相关文章:

javascript - for 循环内的 Gulp 流无法正常工作

python - MongoDB 中是否有等效的 redis 命令管道?

reactjs - React Native 工具可以直观地跟踪重新渲染?

javascript - 导入文件需要时间,代码失败后出现

javascript - 如何解决NodeJS方法优先级问题

mongodb - Mongo 中的套接字超时异常

react-native - 如何在 TabNavigator 的特定屏幕上隐藏标题

React-Native View 以显式设置的宽度/高度呈现,但 flexBasis 为 0

javascript - 如何在nodeJS Express中使用next干净地退出二级函数?

javascript - MongoDB:聚合函数中的字符串字段的 parseFloat ($avg)