【问题标题】:React Native import json file & read the contentReact Native 导入 json 文件并读取内容
【发布时间】:2017-01-06 23:58:09
【问题描述】:

我尝试加载 .json 文件并读取内容。但我得到的只是这样的输出:

这是我的代码:

 import movies from './movies.json';

  /* 
  ... 
  */

  function componentWillMount() {
    return (
      fetch(movies).then((res) => res.json()).then((data) => 
      {this.setState({hugeText: data.something});
      })
    );
  }
  function searchForName(){
     var content = componentWillMount();
     alert(content);
  }

它想以字符串的形式获取真实的内容。

【问题讨论】:

  • 请分享完整代码
  • 警报中显示什么?

标签: json react-native


【解决方案1】:

我认为你不能那样使用 componentWillMount...

componentWillMount() {
  fetch(movies).then((res) => res.json()).then((data) => { 
    this.setState({hugeText: data.something});
  });
}

searchForName() {
  alert(this.state.hugeText);
}

【讨论】:

    【解决方案2】:

    首先,不要使用ComponentWillMount

    来自the docs

    UNSAFE_componentWillMount() 在挂载之前被调用。它 在 render() 之前调用,因此同步调用 setState() 在这种方法中不会触发额外的渲染。一般来说,我们 建议使用 constructor() 来初始化状态。

    避免在此方法中引入任何副作用或订阅。 对于这些用例,请改用 componentDidMount()。

    现在,在您的组件中设置一个状态变量,以保存您将从该 API 调用收到的值:

    constructor(props){
      super(props);
      this.state = { hugeText: '' }
    }
    

    如果您只想将对象呈现为字符串,请使用:

    JSON.stringify(your_object_here)
    

    像这样使用它:

    function componentDidMount() {
      fetch(movies).then((res) => res.json())
        .then((data) => {
          this.setState({hugeText: JSON.stringify( data.something ) } , () => {
            alert(this.state.hugeText); // This will happen AFTER the state has been set
          });
        })
    }
    

    你可以在你的渲染函数中使用this.state.hugeText

    也可以在the setState API 阅读。

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 2017-02-19
      • 2018-09-21
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多