我试图每秒将我的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
});
}
}
}
答案 0 :(得分:0)
简单的方法;
this.setState({timeLeft: this.state.timeLeft - 1});
答案 1 :(得分:0)
像++和 - 这样的增量工作者不会工作。只要您想根据以前的状态值更新状态,就应该使用这种语法。
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
}
答案 2 :(得分:0)
因为--
在分配了对象中的 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--
。