我试图每秒将我的 timeLeft
属性减少一个。在startRecording
函数中,我称为startTimer
方法,但似乎无法使状态减小。我究竟做错了什么?谢谢!
class NimbusCamera extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
navigator: PropTypes.object.isRequired
}
state = {
camera: {
aspect: Camera.constants.Aspect.fill,
captureTarget: Camera.constants.CaptureTarget.disk,
type: Camera.constants.Type.front,
captureMode: Camera.constants.CaptureMode.video,
captureAudio: true,
flashMode: Camera.constants.FlashMode.auto
},
isRecording: false,
timeLeft: 30,
reachedLimit: false
}
startTimer = () => {
console.log('Starting timer...')
let timerId = setInterval(countdown, 1000); // Run function every second
const countdown = () => {
console.log('Counting down...')
if (this.state.timeLeft === 0) {
clearTimeout(timerId);
this.setState({isRecording: false})
} else {
console.log(Decrementing...)
this.setState({timeLeft: this.state.timeLeft - 1});
}
}
}
render() {
console.log(this.state)
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={this.state.camera.aspect}
type={this.state.camera.type}
captureAudio={this.state.camera.captureAudio}
flashMode={this.state.camera.flashMode}
>
<Text>{this.state.timeLeft}</Text>
<Text style={styles.capture} onPress={this.startRecording.bind(this)}>[CAPTURE]</Text>
<Text style={styles.capture} onPress={this.stopRecording.bind(this)}>[STOP]</Text>
</Camera>
</View>
);
}
startRecording = () => {
if (this.camera) {
this.camera.capture({mode: Camera.constants.CaptureMode.video})
.then((data) => this.props.dispatch(getPath(data.path)))
.catch(err => console.error(err));
this.startTimer();
this.setState({
isRecording: true
});
}
}
stopRecording = () => {
if (this.camera) {
this.camera.stopCapture();
this.setState({
isRecording: false
});
}
}
}
和 - 无法工作的增量器。每当您要根据以前的状态值更新状态时,都应使用此语法。
this.setState((prevState) => ({ timeLeft: prevState.timeLeft - 1 });
尝试将您的状态对象放入构造函数:
constructor(props){
super(props);
this.state = {
camera: {
aspect: Camera.constants.Aspect.fill,
captureTarget: Camera.constants.CaptureTarget.disk,
type: Camera.constants.Type.front,
captureMode: Camera.constants.CaptureMode.video,
captureAudio: true,
flashMode: Camera.constants.FlashMode.auto
},
isRecording: false,
timeLeft: 30,
reachedLimit: false
}
,因为分配了对象中的 timeLeft
之后的 --
执行。这不是参考,因此setState
的值是在减少之前获得的。
var out = document.getElementById('out');
var outCorrect = document.getElementById('outCorrect');
function setState(newState) {
out.innerHTML = newState.timeLeft;
}
function setStateCorrect(newState) {
outCorrect.innerHTML = newState.timeLeft;
}
var timeLeft = 10;
setState({timeLeft: timeLeft--});
var timeLeftCorrect = 10;
setStateCorrect({timeLeft: timeLeftCorrect - 1});
<span id="out"></span>
<span id="outCorrect"></span>
运行片段,看看原因。 a - b
在分配结果之前执行 a--
是在执行的。
简单的方式;
this.setState(state => {
return {
timeLeft: state.timeLeft - 1,
}
});