我试图在我的组件上显示一些虚拟数据,但我没有看到任何出现在它上面的内容。当我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;
答案 0 :(得分:4)
您未在JSX
内返回map function
内容。
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)
将起作用,但这与问题无关。只想添加答案
答案 1 :(得分:0)
我认为你缺少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'));