React 15 / Redux-更改道具后更新组件

时间:2019-01-09 11:15:13

标签: javascript reactjs react-redux

我有一个有关更新道具的问题。我已将组件连接到Redux存储。当根组件挂载后,我将调用ajax请求并更新存储。我连接的组件会收到新的道具,但不会重新渲染(没有选项)。我知道我可以更新所连接组件的内部状态,但是...是否有必要?

componentWillReceiveProps

receive props
 {agreements: Array(4), actions: {…}} //nextProps
 {agreements: Array(0), actions: {…}} //this.props

点击刷新按钮

refresh {agreements: Array(4), actions: {…}} //this.props

我连接的组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import * as agreementActions from '../../actions/agreementActions';

class ChangeAgreement extends Component {
    constructor(props) {
        super(props);
        this.refresh = this.refresh.bind(this);
    }

    refresh()
    {
        console.log('refresh');
        console.log(this.props);
    }

    componentWillReceiveProps(nextProps, prevState) {
        console.log('receive props');
        console.log(nextProps);
        console.log(this.props);
    }

    render() {
        const { agreements } = this.props;

        return (
            <div>
                Pick agreement
                <button onClick={this.refresh}>Refresh</button>
                <select>
                    {agreements.map((item) => {
                        <option value={item.ID}>{item.NM}</option>;
                    })}
                </select>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        agreements: state.agreements
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(Object.assign({}, agreementActions), dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(ChangeAgreement);

1 个答案:

答案 0 :(得分:1)

您的箭头功能

agreements.map((item) => {
                        <option value={item.ID}>{item.NM}</option>;
                    })

返回undefined。您忘记了return