我的人数据包含动态布尔值。该值自动生成,每次都可以为true或false。
网页每5秒获取一次数据并进行渲染。如果每个人的值都是假,则播放声音。
如果数据增加我有问题,我必须手动添加代码来渲染和播放声音。
这是代码:
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: [],
playSoundPeter: false,
playSoundJohn: false
}
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 });
// extract array results
for (let i = 0; i < this.state.results.length; i++) {
// set playSoundPeter state to true if
// data value equal to false & vice versa
if (this.state.results[0].value === false) {
this.setState({ playSoundPeter: true });
} else {
this.setState({ playSoundPeter: false });
}
// set playSoundJohn state to true if
// data value equal to false & vice versa
if (this.state.results[1].value === false) {
this.setState({ playSoundJohn: true });
} else {
this.setState({ playSoundJohn: false });
}
}
}
render() {
const { results, playSoundPeter, playSoundJohn } = 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>
Peter sound: {(playSoundPeter) ? 'true' : 'false'}
</div>
<div>
John sound: {(playSoundJohn) ? 'true' : 'false'}
</div>
{(playSoundPeter) ? <audio src={Sound} autoPlay /> : ''}
{(playSoundJohn) ? <audio src={Sound} autoPlay /> : ''}
</div>
);
}
}
render(<App />, document.getElementById('root'));
这是demo
在上面的代码中,如果数据增加或减少,我必须手动添加或删除:
playSound状态
条件陈述&amp;的setState
div true或false value
音频声音
如果数据增加,如何自动生成声音代码?
解决更新 demo
答案 0 :(得分:1)
<audio ...>
标签;使用new Audio()
代替声音不是render
所关注的问题,而是getData
的关注
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 });
// your condition here. If John or Peter value is false
if (data.some(d => d.false)) {
var audio = new Audio('audio_file.mp3');
audio.play();
}
}
componentWillUnmount