Reputation: 283
Was working with the code below for sending a list of values to another component -
React.createElement("ul", null,
this.state.stock.map(function (value){
return (React.createElement(Price, { price: value }))
})
)
and then the values will be sent to the component below -
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)
)
}
});
In the above component there is one problem. If I am sending a single value then the conditions are working fine. But, if I use a list of values then the conditions are not working correctly. Checking for last and next values for displaying the triangle arrow top and bottom. While rendering the result, when doing the calculation the values are not getting properly calculated. Is there any way to calculate the values correctly and then show the correct result for every item in the object?
Upvotes: 2
Views: 5631
Reputation: 961
componentWillReceiveProps is deprecated along with componentWillMount and componentWillUpdate. Use getderivedStateFromProps(nextProps, preState) just be careful as this lifecycle method is static and is invoked when your component is instantiated.
Upvotes: 0
Reputation: 12882
You should use componentWillReceiveProps
lifecycle method for this. It receives nextProps
as the parameter, and can access current props by this.props
.
Here is method description:
Invoked when a component is receiving new props. This method is not called for the initial render.
Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.
I've made a fiddle with an example similar to your case, so you can see how it works. I pass props with a components within an interval, and see the dynamics in comparison with previous state:
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] = '-'
}
}
Hope, you will adept it for your case without any problems.
Upvotes: 1