我正在尝试在react native中创建一个应用程序。我将信息存储在数据库中。我使用php通过查询获取数据库的信息。
然后我使用访存来获取信息,并且能够获取信息并将其显示为文本。我想将数据作为变量,以便可以与本机声音一起使用。
这是我的反应本机代码
constructor(props){
super(props);
this.state = {
playState:'paused', //playing, paused
playSeconds:0,
duration:0,
FileUrlHolder: ''
}
this.sliderEditing = false;
}
componentDidMount(){
fetch('http://f10f7e2e.ngrok.io/Filter.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
// Getting the id.
id: this.props.navigation.state.params.FlatListClickItemHolder
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
FileUrlHolder: responseJson[0].FileUrl
});
}).catch((error) => {
console.error(error);
});
}
componentWillUnmount(){
play = async () => {
if(this.sound){
this.sound.play(this.playComplete);
this.setState({playState:'playing'});
}else{
const filepath = this.state.FileUrlHolder;
console.log('[Play]', filepath);
//Alert.alert('id ' + filepath);
this.sound = new Sound(filepath, (error) => {
if (error) {
console.log('failed to load the sound', error);
Alert.alert('Notice', 'audio file error. (Error code : 1)');
this.setState({playState:'paused'});
}else{
this.setState({playState:'playing', duration:this.sound.getDuration()});
this.sound.play(this.playComplete);
}
});
}
}
我的json看起来像
[{"FileUrl":"John_30th_sept_2018.mp3"}]
答案 0 :(得分:0)
执行response.json()
时,将返回使用响应主体创建的对象。在您的情况下,该对象将是一个包含具有FileUrl
属性的对象的数组。您不需要JSON.parse()
,因为它已经被解析为一个对象,这就是为什么会出现错误的原因。您的代码应该可以工作,到底出了什么问题?您确定后端会返回正确的数据吗?