简体   繁体   English

有没有办法从 json 中获取一个值作为 react native 中的变量

[英]is there a way to get a value from json as a variable in react native

I am trying to create an app in react native.我正在尝试在 React Native 中创建一个应用程序。 I have information stored in a database.我有信息存储在数据库中。 I use php to get the information for the database using a query.我使用 php 通过查询来获取数据库的信息。

I then use fetch to get the information and I am able to get the information and display it as text.然后我使用 fetch 来获取信息,我能够获取信息并将其显示为文本。 I would like to have the data as a variable so that I can use it with react-native sound.我想将数据作为变量,以便我可以将它与本机声音一起使用。

Here is my react native code这是我的反应本机代码

 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); } }); } }

My json looks like我的 json 看起来像

 [{"FileUrl":"John_30th_sept_2018.mp3"}]

When you do response.json() , you get back an object that was created using the body of the response.当您执行response.json() ,您会返回一个使用响应正文创建的对象。 In your case this object will be an array containing an object with a FileUrl property.在您的情况下,此对象将是一个包含具有FileUrl属性的对象的数组。 You don't need to JSON.parse() it because it has already been parsed into an object, this is why you get an error.您不需要JSON.parse()它,因为它已经被解析为一个对象,这就是您收到错误的原因。 Your code should work, what exactly is the problem?您的代码应该可以工作,究竟是什么问题? Are you certain your backend is returning the correct data?您确定您的后端正在返回正确的数据吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM