反应独特的“键"错误 [英] React unique "key" error

查看:20
本文介绍了反应独特的“键"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 React 中的待办事项列表教程并遇到以下错误,我花了很长时间却找不到错误..这是错误和组件的代码以及这个是课程仓库的代码(此提交出现问题):

https://github.com/andrewjmead/react-todo-app/commit/0521f151705f78cb9f8d69262eb093f1431cb9ca

非常感谢任何帮助.

警告:数组或迭代器中的每个子项都应该有一个唯一的键"属性.检查TodoList的render方法.有关详细信息,请参阅 fb.me/react-warning-keys.

终端也有错误,对于扩展运算符 TOGGLE_TODO

return {...todo,//这里完成:下一个完成,完成时间:下一个完成?时刻().unix():未定义};var React = require('react');var { connect } = require('react-redux');从 'Todo' 导入 Todo;var TodoAPI = require('TodoAPI');export var TodoList = React.createClass ({渲染:函数(){var { todos, showCompleted, searchText } = this.props;var renderTodos = () =>{如果(todos.length === 0){返回 (<p className="container__message">没有任务</p>);}return TodoAPI.filterTodos(todos, showCompleted, searchText).map((todo) => {返回 (//添加唯一的关键道具以跟踪各个组件<Todo key={todo.id} {...todo}/>);});};返回 (<div>{renderTodos()}

);}});导出默认连接((状态) =>{返回状态;})(待办事项列表);

减速器:

var uuid = require('uuid');var moment = require('moment');export var searchTextReducer = (state = '', action) =>{开关(动作.类型){案例SET_SEARCH_TEXT":返回 action.searchText;默认:返回状态;};};export var showCompletedReducer = (state = false, action) =>{开关(动作.类型){案例TOGGLE_SHOW_COMPLETED":返回!状态;默认:返回状态;};};export var todosReducer = (state = [], action) =>{开关(动作.类型){案例ADD_TODO":返回 [...状态,{文字:动作.文字,id: uuid(),完成:假,createdAt: 时刻().unix(),完成时间:未定义}];案例TOGGLE_TODO":返回 state.map((todo) => {if(todo.id === action.id) {var nextCompleted = !todo.completed;返回 {...去做,完成:下一个完成,完成时间:下一个完成?时刻().unix():未定义};} 别的 {返回待办事项;}});案例ADD_TODOS":返回 [...状态,...action.todos];默认:返回状态;}};网络包:var webpack = require('webpack');模块.出口 = {入口: ['脚本!jquery/dist/jquery.min.js','script!foundation-sites/dist/js/foundation.min.js','./app/app.jsx'],外部:{jquery: 'jQuery'},插件: [新的 webpack.ProvidePlugin({'$': 'jquery','jQuery':'jquery'})],输出: {路径:__目录名,文件名:'./public/bundle.js'},解决: {根:__dirname,模块目录:['节点模块','./应用程序/组件','./app/api'],别名:{applicationStyles: 'app/styles/app.scss',动作:'app/actions/actions.jsx',减速器:'app/reducers/reducers.jsx',configureStore: 'app/store/configureStore.jsx'},扩展名:['', '.js', '.jsx']},模块: {装载机: [{loader: 'babel-loader',询问: {预设:['反应','es2015']},测试:/.jsx?$/,排除:/(node_modules|bower_components)/}]},开发工具:'廉价模块评估源地图'};

解决方案

node-uuid is deprecated, check here: https://www.npmjs.com/package/uuid

您可以通过安装 uuid 来更新您的 package.json 并查看是否有帮助:

npm 安装 uuid

不要忘记更新 var uuid = require('node-uuid');到 var uuid = require('uuid');在您的其他文件中.

附言当您运行 webpack 时,您的终端中是否有任何错误?

I'm going through a tutorial for todo list in React and ran into the following error, I have spent quite a time and just can't find the mistake..here is the error and the code for the component and this is the code for the course repo(problem appears on this commit):

https://github.com/andrewjmead/react-course-todo-app/commit/0521f151705f78cb9f8d69262eb093f1431cb9ca

Any help much appreciated.

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of TodoList. See fb.me/react-warning-keys for more information.

Also there is an error in terminal, for the spread operator in case TOGGLE_TODO

return {
...todo, // here
completed: nextCompleted,
completedAt: nextCompleted ? moment().unix() : undefined
};

var React = require('react');
var { connect } = require('react-redux');
import Todo from 'Todo';
var TodoAPI = require('TodoAPI');

export var TodoList = React.createClass ({
    render: function() {
        var { todos, showCompleted, searchText } = this.props;
        var renderTodos = () => {
            if(todos.length === 0) {
                return (
                    <p className="container__message">No tasks</p>
                );
            }
            return TodoAPI.filterTodos(todos, showCompleted, searchText).map((todo) => {
                return (
                    //add unique key prop to keep track of individual components
                    <Todo key={todo.id} {...todo} />
                );
            });
        };
        return (
            <div>
                {renderTodos()}
            </div>
        );  
    }
});

export default connect(
    (state) => {
        return state;
    }
)(TodoList);

Reducers:

var uuid = require('uuid');
var moment = require('moment');

export var searchTextReducer = (state = '', action) => {
    switch (action.type) {
        case 'SET_SEARCH_TEXT':
            return action.searchText;
        default: 
            return state;
    };
};

export var showCompletedReducer = (state = false, action) => {
    switch (action.type) {
        case 'TOGGLE_SHOW_COMPLETED':
            return !state;
        default: 
            return state;
    };    
};

export var todosReducer = (state = [], action) => {
    switch(action.type) {
        case 'ADD_TODO':
            return [
                ...state,
                {
                    text: action.text,
                    id: uuid(),
                    completed: false,
                    createdAt: moment().unix(),
                    completedAt: undefined                   
                }
            ];
        case 'TOGGLE_TODO':
            return state.map((todo) => {
                if(todo.id === action.id) {
                    var nextCompleted = !todo.completed;

                    return {
                        ...todo,
                        completed: nextCompleted,
                        completedAt: nextCompleted ? moment().unix() : undefined
                    };
                } else {
                    return todo;
                }
            });
        case 'ADD_TODOS':
            return [
                ...state,
                ...action.todos
            ];
        default: 
            return state;
    }
};


Webpack:

var webpack = require('webpack');

module.exports = {
  entry: [
    'script!jquery/dist/jquery.min.js',
    'script!foundation-sites/dist/js/foundation.min.js',
    './app/app.jsx'
  ],
  externals: {
      jquery: 'jQuery'
  },
  plugins: [
      new webpack.ProvidePlugin({
          '$': 'jquery',
          'jQuery': 'jquery'
      })
  ],
  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  resolve: {
    root: __dirname,
    modulesDirectories: [
        'node_modules',
        './app/components',
        './app/api'
    ],
    alias: {
        applicationStyles: 'app/styles/app.scss',
        actions: 'app/actions/actions.jsx',
        reducers: 'app/reducers/reducers.jsx',
        configureStore: 'app/store/configureStore.jsx'
    },
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015']
        },
        test: /.jsx?$/,
        exclude: /(node_modules|bower_components)/
      }
    ]
  },
  devtool: 'cheap-module-eval-source-map'
};

解决方案

node-uuid is deprecated, check here: https://www.npmjs.com/package/uuid

You can update your package.json by installing uuid and see if it helps:

npm install uuid

Just don't forget to update var uuid = require('node-uuid'); to var uuid = require('uuid'); in your other files.

P.S. Do you get any errors in your terminal when you run a webpack?

这篇关于反应独特的“键"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆