我正在学习 React,我正在为自己创建一个应用程序来跟踪我的学习。一切正常。
在我的应用程序中,我有一个基于类的组件,我必须在其中将道具传递给状态。但是,我了解到我不应该在基于类的组件中将道具传递给状态,因为我可能会在某处更改状态。但是我不知道如何让我的代码工作而不像我正在做的那样传递道具来声明。我是自学的,所以没有老师可以请教,因此 StackOverflow 是我最好的导师。预先感谢您的帮助。
这是我的代码。我将它相应地更改为下面的答案,现在它工作正常,但我的代码中有什么我应该更改或避免的吗?
import React from 'react';
import SubjectFrom from './SubjectForm';
import {startSubject} from '../actions/subjectAction';
import {connect} from 'react-redux';
class BeginSubject extends React.Component{
constructor(props){
super(props);
this.state={
timeRun:0,
onFinish:'',
buttonChange:'start',
timer:null
}
}
componentWillMount(){
this.setState({timeRun:this.props.subject?this.props.subject.hour*60*60+this.props.subject.minute*60:0,});
}
componentWillUnmount(){
let hour = Math.floor(this.state.timeRun / (60 * 60));
let minute= Math.floor((this.state.timeRun % (60 * 60)) / 60);
this.onPause();
if(this.props.subject){
this.props.dispatch(startSubject(this.props.subject.id,{hour,minute}))
console.log(this.props.subject.id)
}
}
onStart=()=>{
clearInterval(this.timer)
this.timer = setInterval(()=>{
let count=this.state.timeRun
count--
if(count<0){
this.setState({onFinish:'well Done'})
clearInterval(this.timer);
return;
}
let hourleft = Math.floor(count / (60 * 60));
let minuteleft = Math.floor((count % (60 * 60)) / 60);
let secondleft = count % 60;
this.setState({onFinish:`you have ${hourleft} hour ${minuteleft} minute and ${secondleft} second until reaching your goal`});
this.setState({timeRun:count})
},1000)
}
onPause=()=>{
clearInterval(this.timer)
let time = this.props.subject?this.props.subject.hour*60*60+this.props.subject.minute*60:0;
if(this.state.timeRun<time){
this.setState({buttonChange:'resume'})
return;
}
}
onReset=()=>{
const resetConfirm=confirm('you have not finished, do you want to reset?')
if(resetConfirm===true){
clearInterval(this.timer)
this.setState({timeRun:this.props.subject?this.props.subject.hour*60*60+this.props.subject.minute*60:0,
onFinish:'',
buttonChange:'start',
timer:null})
}
}
render(){
return(
<div>
<p>{this.props.subject?this.props.subject.subjectName:'there is nothing to do for now'}</p>
<p>{this.props.subject?`you have ${this.props.subject.hour} hour and ${this.props.subject.minute} minute to work`:'there is no time set'}</p>
<button onClick={this.onStart}>{this.state.buttonChange}</button>
<button onClick={this.onPause}>pause</button>
<button onClick={this.onReset}>reset</button>
<p>{this.state.onFinish}</p>
</div>
)
}
};
const mapStateToProps=(state,props)=>{
return{
subject:state.subjects.find((subject)=>subject.id===props.match.params.id)
};
}
export default connect(mapStateToProps)(BeginSubject)