我正在浏览React中的todo列表教程并遇到以下错误,我花了很长时间才找不到错误..错误和组件的代码和这个是课程回购的代码(问题出现在此提交中):
https://github.com/andrewjmead/react-course-todo-app/commit/0521f151705f78cb9f8d69262eb093f1431cb9ca
任何帮助都非常感激。
警告:数组或迭代器中的每个子节点都应该有一个唯一的“key”prop。检查TodoList
的呈现方法。有关更多信息,请参见fb.me/react-warning-keys。
终端也有错误,对于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);
减速:
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'
};
答案 0 :(得分:4)
在React中,当你渲染多个相同的组件(在你的情况下,todos)时,你需要为它们中的每一个添加一个唯一的密钥,因为React需要知道它们将如何成为在虚拟dom中处理。
你可以做各种事情来解决这个问题:
在for循环中,创建一个索引变量,并在每次循环结束时将其递增1,然后将其设置为每个渲染组件的键。
如果您从api中获取待办事项,请为每个待办事项设置一个ID并将其用作您的组件密钥。
使用随机数生成器在每个待办事项上设置唯一键。
最好的方法是#2和#3,我知道在你的情况下你试图做#2(通过todo id设置密钥),但我认为它是未定义的,请检查它
另一种解决方案是在每个渲染的组件/待办事项上使用uuid。
为此,您可以安装node-uuid。
运行:npm i --save node-uuid
然后在您的文件中执行导入:import uuid from 'node-uuid'
或const uuid = require('node-uuid')
现在将代码更改为:
return TodoAPI.filterTodos(todos, showCompleted, searchText).map((todo) => {
return (
//add unique key prop to keep track of individual components
<Todo key={uuid()} {...todo} />
);
});
然后你很高兴去。
答案 1 :(得分:3)
node-uuid,请点击此处:https://www.npmjs.com/package/uuid
您可以通过安装uuid来更新您的package.json,看看它是否有帮助:
npm install uuid
不要忘记更新var uuid = require(&#39; node-uuid&#39;); to var uuid = require(&#39; uuid&#39;);在你的其他文件中。
P.S。当你运行webpack时,你的终端是否有任何错误?
答案 2 :(得分:2)
我打赌todo.id
是undefined
,因此不是唯一的。你可以在你的例子中加入todos
吗?
答案 3 :(得分:2)
您可以将index
参数添加到map
函数中,然后将该索引传递到Todo
组件:
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, index) => { // here <====
return (
//add unique key prop to keep track of individual components
<Todo key={`key-${index}`} {...todo} />
);
});
};
return (
<div>
{renderTodos()}
</div>
);
}
});