【问题标题】:is there a way to get a value from json as a variable in react native有没有办法从 json 中获取一个值作为 react native 中的变量
【发布时间】:2019-12-19 16:39:00
【问题描述】:

我正在尝试在本机反应中创建一个应用程序。我将信息存储在数据库中。我使用 php 通过查询来获取数据库的信息。

然后我使用 fetch 来获取信息,我能够获取信息并将其显示为文本。我想将数据作为变量,以便我可以将它与反应原生声音一起使用。

这是我的反应原生代码

  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"}]

【问题讨论】:

  • 可以使用JSON.parse("YOUR JSON STRING")将json字符串转成对象
  • 这将如何运作?
  • 类似:.then((responseJson) => { let jsonObj = JSON.parse(responseJson); this.setState({ FileUrlHolder: jsonObj[0].FileUrl }); })
  • 这会导致错误,SyntaxError: JSON Parse error: Unexpected identifier "object"
  • 看起来responseJson 是一个对象。如果是string,请执行console.log(typeof responseJson[0]) JSON.parse。我不确定我是否很好地理解了你的问题。

标签: javascript react-native react-native-sound


【解决方案1】:

当您执行response.json() 时,您会返回一个使用响应正文创建的对象。在您的情况下,此对象将是一个数组,其中包含一个具有 FileUrl 属性的对象。你不需要JSON.parse()它,因为它已经被解析成一个对象,这就是你得到一个错误的原因。您的代码应该可以工作,到底是什么问题?您确定您的后端返回的数据正确吗?

【讨论】:

  • 是的,我已经检查了我的后端并返回了正确的信息,我似乎只能将我返回的信息作为短信使用,而不是变量
  • 我认为这可能是导致问题的行 const filepath = this.state.FileUrlHolder;当我尝试 console.log 时,文件路径没有打印到控制台
猜你喜欢
  • 2021-07-19
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多