मैं अभी भी रिएक्ट में काफी नया हूं, लेकिन मैं धीरे-धीरे पीस रहा हूं और मैंने कुछ का सामना किया है जो मैं फंस गया हूं।
मैं प्रतिक्रिया में एक "टाइमर" घटक बनाने की कोशिश कर रहा हूं, और ईमानदार होने के लिए मुझे नहीं पता कि क्या मैं यह अधिकार (या कुशलतापूर्वक) कर रहा हूं। नीचे मेरी कोड में, मैं एक वस्तु वापस जाने के लिए राज्य की स्थापना की { currentCount: 10 }और साथ कर रहा है componentDidMount, componentWillUnmountऔर renderऔर मैं केवल 10 से 9 तक "उलटी गिनती" करने के लिए राज्य प्राप्त कर सकते हैं।
दो-भाग का प्रश्न: मैं क्या गलत कर रहा हूँ? और, वहाँ setTimeout का उपयोग कर (बजाय का उपयोग कर के बारे में जाने के लिए एक अधिक कुशल तरीका है componentDidMountऔर componentWillUnmount)?
पहले ही, आपका बहुत धन्यवाद।
import React from 'react';
var Clock = React.createClass({
getInitialState: function() {
return { currentCount: 10 };
},
componentDidMount: function() {
this.countdown = setInterval(this.timer, 1000);
},
componentWillUnmount: function() {
clearInterval(this.countdown);
},
timer: function() {
this.setState({ currentCount: 10 });
},
render: function() {
var displayCount = this.state.currentCount--;
return (
<section>
{displayCount}
</section>
);
}
});
module.exports = Clock;
bind(this)अब जरूरत नहीं है, प्रतिक्रिया अब अपने दम पर करती है।