【发布时间】:2017-02-22 14:00:43
【问题描述】:
我是 reactjs 的新手
我想在员工页面加载 (http://localhost:8080/employees/3) 时获取 id 为 3 的员工详细信息。
我的代码:
EmpPage.js
import React,{PropTypes} from 'react';
import {connect} from 'react-redux';
import {getEmp} from '../../actions/empActions';
import configureStore from '../../store/configureStore';
const store = configureStore();
class EmpPage extends React.Component {
constructor(props, context) {
super(props, context);
}
componentWillMount () {
var id = this.props.params.id;
store.dispatch(getEmp({'userId': id}));
}
render() {
const emp = this.props.emp;
console.log('emp================', emp); //issue: get blank object
return (
<div>
<h1>Emp Page...</h1>
</div>
)
}
}
EmpPage.propTypes = {
emp: PropTypes.object.isRequired,
children: PropTypes.object
};
function mapStateToProps(state, ownProps) {
return {
emp: state.emp
};
}
export default connect(mapStateToProps)(EmpPage);
我想获取员工详细信息,我得到的是空白对象
render() {
const emp = this.props.emp;
console.log('emp================', emp); //issue: get blank object
return (
<div>
<h1>Emp Page...</h1>
</div>
)
}
调用componentWillMount ()时API响应成功,但mapStateToProps()中没有设置状态。
但是当我调用 dispatch store.dispatch(getEmp({'userId': id})); form index.js instated of componentWillMount () 然后状态 emp: state.emp 在 mapStateToProps 中设置成功。
所以,我想在页面加载时获取员工详细信息并将其显示在 html 页面中。
【问题讨论】:
-
mapStateToProps (
console.log(state)) 内部的状态是什么? -
@HonzaHaering : 获取空白对象