2016-07-22 52 views
2

用的代码的工作下面,用于发送值的列表到另一部件 -如何检查在阵营前面和后面的值不同?

React.createElement("ul", null, 
    this.state.stock.map(function (value){ 
    return (React.createElement(Price, { price: value })) 
    }) 
) 

,然后这些值将在下文被发送到部件 -

var initialPrice = null; 
var iconClass = ' '; 
var counter = 0; 
var Price = React.createClass({ 
    render: function() { 
    var newPrice = this.props.price.l_fix; 
    var finalPrice = newPrice - initialPrice; 

    if(finalPrice < 0) { 
     iconClass = 'bg-danger glyphicon glyphicon-triangle-bottom text-danger'; 
    } 
    else if(finalPrice > 0) { 
     iconClass = 'glyphicon glyphicon-triangle-top text-success bg-success'; 
    } 

    initialPrice = newPrice; 

    return (
     React.createElement("li", null, this.props.price.t," (",this.props.price.e," ) - "," Current Price : ",this.props.price.l_fix," ", 
         React.createElement("span", { className: iconClass, "aria-hidden": "true" }),"  Date : ",this.props.price.lt) 
       ) 
     } 
    }); 

在上述组分存在一个问题。如果我发送单个值,那么条件工作正常。但是,如果我使用值的列表,则条件无法正常工作。检查显示三角形箭头顶部和底部的最后和下一个值。在渲染结果时,在进行计算时,值得不到正确的计算。有什么方法可以正确计算出这些值,然后显示对象中每个项目的正确结果吗?

回答

1

您应该使用这个componentWillReceiveProps生命周期的方法。它接收nextProps作为参数,并且可以通过访问this.props当前道具。

这里是方法描述:

时调用组件被接收到新的道具。此方法不用于初始渲染。

使用此为契机,反应以道具过渡渲染()之前通过更新使用this.setState()的状态下调用。旧的道具可以通过this.props访问。在这个函数中调用this.setState()不会触发额外的渲染。

我做了类似于你的情况的例子的fiddle,所以你可以看到它是如何工作的。我通过道具与区间内的成分,看看动力学与以前的状态比较:

componentWillReceiveProps: function(nextProps) { 
    let dynamics = ['=', '='] 

    for(let i=0; i < 2; i++) { 
     console.log(i) 
     if (nextProps.values[i] > this.props.values[i]) { 
     dynamics[i] = '+' 
     } 
     else if (nextProps.values[i] === this.props.values[i]) { 
     dynamics[i] = '=' 
     } 
     else { 
     dynamics[i] = '-' 
     } 
    } 

希望,你会娴熟它为你的情况没有任何问题。

+1

感谢@Lazarev亚历山大,会尽量做到。 – Worker

+0

您在提琴手只取两个值。主要问题有'n'值。如何获得将要调用循环的总次数。我尝试使用'(this.props).length',但它没有解决。其他解决方案? – Worker

+0

https://jsfiddle.net/k9zbrxtx/8/在这里你应该使用'this.props.values.length'或'nextProps.values.length' –