【发布时间】:2018-04-13 03:59:25
【问题描述】:
我有包含动态布尔值的人员数据。该值是自动生成的,每次都可以为真或假。
网页每 5 秒获取一次数据并进行渲染。如果每个人的值为 false,则播放声音。
这是代码:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Sound from './Mp3';
const data = [
{
id: '1',
name: 'Peter',
value: true
},
{
id: '2',
name: 'John',
value: false
}
];
class App extends Component {
state = {
results: [],
}
componentDidMount() {
this.getData()
// get data every 5 sec
setInterval(this.getData, 5000);
}
getData = () => {
// generate random value
data[0].value = Math.random() >= 0.5;
data[1].value = Math.random() >= 0.5;
// set results state to data
this.setState({ results: data });
// condition if John or Peter value is false
if (data.some(d => d.value === false)) {
var audio = new Audio(Sound);
// play a sound
audio.play();
}
}
render() {
const { results } = this.state;
return (
<div>
{results.map(item => {
return (
<div key={item.id}>
<div>
Name: {item.name}
</div>
<div>
Value: {item.value.toString()}
</div>
<br />
</div>
)
})}
</div>
);
}
}
render(<App />, document.getElementById('root'));
这是demo
使用上面的代码,如果每个人的值为 false,则每次播放声音。
如何只在第一次假值后才播放声音?
我的意思是,如果第一个渲染的 John 值为 false,则播放声音,如果 5 秒后 John 值仍然为 false,则在值恢复为 true 并再次更改为 false 后不播放声音。
我期望的结果:
// first rendered
Name: Peter
Value: true
Name: John
Value: false // play a sound
// second (5 seconds later)
Name: Peter
Value: true
Name: John
Value: false // don't play a sound
// third (10 seconds later)
Name: Peter
Value: true
Name: John
Value: true // don't play a sound
// fourth (15 seconds later)
Name: Peter
Value: true
Name: John
Value: false // play a sound
...
【问题讨论】:
-
第一种情况 - John 有一个真正的价值,但你的要求是
With the code above, the sound is played every time if the value on each person is false.你能解释一下吗? -
先生。 Asiniy,是的,Peter 有一个 true 值,John 有一个 false 值,它会每 5 秒自动生成随机的 true 或 false。所以对于第一次渲染,声音只播放 John false 值。
-
对不起 Asiniy 先生,我的代码数据和我期望的结果数据看起来不同。我已经更新了我的问题。
标签: javascript reactjs html5-audio