无法使用 react 和 redux 在组件中显示数据
2017-05-10
252
我尝试在组件上显示一些虚拟数据,但看不到任何内容。当我
console.log
时,我得到了预期结果
[object Object]
。
我认为我的
actions
、
actionCreators
和
reducers
中缺少了某些内容。
#actions/types.js
export const FETCH_USERS = 'fetch_users';
#actions/index.js
import {
FETCH_USERS
} from './types';
const user = [
{ name: 'D/S' },
{ name: 'Bob' },
{ name: 'Juan' }
]
export function fetchUsers() {
return { type: FETCH_USERS, payload: user }
}
#reducers/users_reducer.js
import {
FETCH_USERS
} from '../actions/types';
export default function (state = [], action) {
switch(action.type) {
case FETCH_USERS:
return [ ...state, ...action.payload ];
}
return state;
}
#reducers/index.js
import { combineReducers } from 'redux';
import UsersReducer from './users_reducer';
const rootReducer = combineReducers({
users: UsersReducer
});
export default rootReducer;
# components/UserList.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import styles from './App.css';
import * as actions from '../actions';
class UserList extends Component {
componentWillMount() {
const fetchedUsers = this.props.fetchUsers() ? this.props.fetchUsers() : 'No users at this time';
console.log(`This is the list of users: ${fetchedUsers}`); // <= here I just get [object Object]
}
renderUser(user) {
<div className={ styles.card }>
<h4>{ user.name }</h4>
<p>Lego Inc</p>
<a>Email</a>
</div>
}
render() {
const userList = this.props.users.map(this.renderUser);
console.log(`${userList}`);
return (
<div>
{ userList }
</div>
)
}
}
function mapStateToProps(state) {
return { users: state.users }
}
export default connect(mapStateToProps, actions)(UserList);
# components/App.js
import React from 'react';
import styles from './App.css';
import UserList from './UserList';
const App = () => (
<div className={''}>
<h2>React Redux middleware</h2>
<div>
<UserList />
</div>
</div>
);
export default App;
2个回答
您未在
map 函数
中返回
JSX
内容。
renderUser(user) {
return ( // Added a return statement here
<div className={ styles.card }>
<h4>{ user.name }</h4>
<p>Lego Inc</p>
<a>Email</a>
</div>
)
}
此外,您还需要使用 console.log(
${userList
),
console.log(userList)
可以工作,但这与问题无关。只是想补充答案
Shubham Khatri
2017-05-10
我认为您缺少 ReactDOM.render 以便将组件实际安装到 DOM。
# components/App.js
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './App.css';
import UserList from './UserList';
const App = () => (
<div className={''}>
<h2>React Redux middleware</h2>
<div>
<UserList />
</div>
</div>
);
ReactDOM.render(App, document.getElementById('react-app'));
Edgar Pino
2017-05-10