我是全新的反应,我正在按照教程。在本教程中,我有以下名为user-list.js的组件:
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
class UserList extends Component {
createListItems() {
return this.props.users.map((user) => {
return (
<li>{user.first}</li>
);
});
}
render() {
return (
<ul>
{this.createListItems()}
</ul>
);
}
}
function mapStateToProps(state) {
return {
users: state.users
};
}
export default connect(mapStateToProps)(UserList);
这是我的reducer-users.js
export default function() {
return [
{
id: 1,
first: 'Bucky',
last: 'Roberts',
age: 71,
description: 'Bucky is a React developer anbd Youtuber',
thumbnail: 'http://i.imgur.com/7yUvePI.jpg'
},
{
id: 2,
first: 'Joby',
last: 'Wasilenko',
age: 27,
description: 'Joby loves the Packers, cheese and turtles',
thumbnail: 'http://i.imgur.com/52xRlm8.jpg'
},
{
id: 3,
first: 'Madison',
last: 'Williams',
age: 24,
description: 'Madi likes her dog but it is really annoying.',
thumbnail: 'http://i.imgur.com/4EMtxHB.jpg'
}
]
}
现在我在控制台中收到错误:
未捕获的TypeError:无法读取属性&#39; map&#39;未定义的
我不明白自己做错了什么,我删除了地图功能并返回了其他任何数据,但它工作正常,除非它试图映射数据。
答案 0 :(得分:0)
在React Components中使用ES6语法时,在构造函数中,您需要绑定在类上定义的任何自定义方法。
将以下内容添加到UserList定义
constructor(props) {
super(props);
this.createListItems = this.createListItems.bind(this);
}
你应该好好去。如果您不喜欢这样做,您还可以恢复为React.createClass({})方法来创建组件类。
答案 1 :(得分:0)
你应该有类似的东西让你的代码正常工作。
// user reducer file
const initialState = [
{
id: 1,
first: 'Bucky',
last: 'Roberts',
age: 71,
description: 'Bucky is a React developer anbd Youtuber',
thumbnail: 'http://i.imgur.com/7yUvePI.jpg'
},
{
id: 2,
first: 'Joby',
last: 'Wasilenko',
age: 27,
description: 'Joby loves the Packers, cheese and turtles',
thumbnail: 'http://i.imgur.com/52xRlm8.jpg'
},
{
id: 3,
first: 'Madison',
last: 'Williams',
age: 24,
description: 'Madi likes her dog but it is really annoying.',
thumbnail: 'http://i.imgur.com/4EMtxHB.jpg'
}
];
export default function usersReducer(state, action) {
return state;
}
// root reducer file
import { combineReducers } from 'redux';
import usersReducer from 'your path to users reducer file'
export default function rootReducer() {
return combineReducers({
users: usersReducer,
});
}
// store file
import { createStore } from 'redux';
import rootReducer from 'path to root reducer file';
const store = createStore(rootReducer());
export default store;