【问题标题】:get employee detail by id in reactjs-redux在 reactjs-redux 中通过 id 获取员工详细信息
【发布时间】: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.empmapStateToProps 中设置成功。

所以,我想在页面加载时获取员工详细信息并将其显示在 html 页面中。

【问题讨论】:

  • mapStateToProps (console.log(state)) 内部的状态是什么?
  • @HonzaHaering : 获取空白对象

标签: api reactjs redux


【解决方案1】:

看起来您正在创建一个新商店并发送给它:

const store = configureStore();

...

store.dispatch(getEmp({'userId': id}));

而不是直接点击store,您应该通过定义connectmapDispatchToProps arg 将您的动作创建者绑定到&lt;Provider&gt; 提供的商店。

编辑:相关更改如下所示:

componentWillMount () {
    var id = this.props.params.id;
    this.props.getEmp({'userId': id}));
}


export default connect(mapStateToProps, { getEmp })(EmpPage);

【讨论】:

  • 你的意思是打电话给getEmp({'userId': id}
  • 您的意思是从 mapDispatchToProps 调用 getEmp({'userId': id}。如果是,如何从 mapDispatchToProps 函数中的 URL 获取 id?
  • 谢谢......它的工作......你知道 reactjs-redux 的任何不错的教程链接,我将在那里学习 react-redux。
猜你喜欢
  • 2020-10-08
  • 1970-01-01
  • 2023-03-23
  • 2020-11-22
  • 1970-01-01
  • 2018-10-25
  • 2016-04-24
相关资源
最近更新 更多