状态道具更改时,React组件不会更新

时间:2016-12-06 17:29:09

标签: reactjs redux immutable.js

我正在尝试将股票列表呈现为按钮列表,我正在使用mapStateToProps并连接以将我的react组件连接到redux存储。这是执行渲染的组件

import React, {Component} from 'react';
import {connect} from 'react-redux';

class StockList extends Component {
    super(props){
        constructor(props);
        this.renderButton = this.renderButton.bind(this);
    }

    renderButton(stock){
        return(
            <button key={stock} type='button' className='btn btn-primary stock-btn'>
                {stock}
                <span className='glyphicon glyphicon-remove' aria-hidden='true'
                onClick={() => this.props.onClick(stock)}></span>
            </button>
        )
    }

    render() {
        if(this.props.stocks){
            return (
                <div>
                    {this.props.stocks.map(stock => {
                        return this.renderButton(stock);
                    })}
                </div>
            )
        }else{
            return(
                <div>Loading...</div>
            )
        }
    }
}

StockList.propTypes = {
    onClick: React.PropTypes.func.isRequired
};

const mapStateToProps = (state) => {
    console.log(state);
    return {
        stocks: state.get(['tickers'])
    }
}

export default connect(mapStateToProps, null)(StockList);

为了确保我的状态正在更新,而不是变异,我使用redux-logger中间件检查状态是否正在发生变化。这是控制台中显示的快照

action @ 22:43:44.408 SET_TICKERS
core.js:111  prev state Map {size: 0, _root: undefined, __ownerID: undefined, __hash: undefined, __altered: false}
core.js:115  action Object {type: "SET_TICKERS", state: Object}state: Objecttickers: Array[3]0: "AAPL"1: "TSLA"2: "GOOGL"length: 3__proto__: Array[0]__proto__: Objecttype: "SET_TICKERS"__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: __proto__()set __proto__: __proto__()
core.js:123  next state Map {size: 1, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}

由于我使用的是Immutable JS,并且状态正在更新,我似乎无法弄清楚为什么我的组件不会更新以显示正确的道具。它不会从最初的undefined改变。

我发现的最接近我的问题的线程是这个github链接 https://github.com/reactjs/redux/issues/585

我在那里检查了解决方案,但没有运气。

1 个答案:

答案 0 :(得分:0)

好的,这是一个简单的语法错误,但我会留在这里以防万一其他人面临同样的问题。

唯一需要改变的是行

const mapStateToProps = (state) => {
    console.log(state);
    return {
        stocks: state.get(['tickers']) //this line needs to change
    }
}

const mapStateToProps = (state) => {
    console.log(state);
    return {
        stocks: state.get('tickers') //remove the brackets denoting array
    }
}