2017-01-09 24 views
0

我是完全陌生的反應,我正在學習一個教程。在本教程中,我有以下組成部分稱爲用戶list.js:Javascript地圖方法在reactjs項目中不起作用

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); 

這裏是我的減速器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' 
    } 
    ] 
} 

現在我得到在控制檯中的錯誤:

Uncaught TypeError: Cannot read property 'map' of undefined

我不明白我在做什麼錯,我刪除了地圖函數並返回了其他任何數據,並且它工作正常,除非它試圖映射數據。

+0

看起來像'this.props.users'不是一個數組。顯示你的根減速器。順便說一下,減速器應該有'(狀態,動作)'簽名,所以重寫你的用戶減速器。 –

回答

0

當您使用React Components的ES6語法時,在您的構造函數中,您需要綁定您在類中定義的任何自定義方法。

以下內容添加到您的UserList的定義

constructor(props) { 
    super(props); 
    this.createListItems = this.createListItems.bind(this); 
} 

,你應該是好去。如果您不喜歡這樣做,您還可以恢復爲創建組件類的React.createClass({})方法。

+0

它沒有工作,行爲是相同的,我一直得到與地圖功能相同的錯誤 – Monica

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;