json - 如何在 React 组件中访问 JSON?

标签 json reactjs

我有一个来自脚本标记的 JSON 对象,如下所示:

  <script type="text/json" id="json-data">
    {'someData': 'Lorem ipsum...'}
  </script>

我希望能够提取此信息并在渲染方法的 React 组件中使用它。

问题似乎是我需要将其设置为 componentWillMount 中的变量:

export default MyReactComponent extends Component {

  componentWillMount() {
    const test = document.getElementById('json-data').innerHTML;
  }

  render() {
    return (
      <div>
        // This is where I would like to use this data.
      </div>
    );
  }

}

这是处理传递此数据的最佳方式吗?如果是这样,我如何在组件的渲染方法中访问这些数据?

谢谢!

最佳答案

将其存储在组件的状态中。渲染方法应该只依赖于 this.statethis.props

冒着过度简化的风险:

  • this.props 从父组件传递
  • this.state 是组件内部的状态

示例

export default MyReactComponent extends Component {

  componentDidMount() {
    this.setState({
        test: JSON.parse(document.getElementById('json-data').innerHTML)
    });
  }

  render() {
    return <div>{this.state.test}</div>;
  },

  getInitialState: function() {
    return {test: {}}
  } 
}

关于json - 如何在 React 组件中访问 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35878942/

相关文章:

javascript - 是否有正确的方法来解析 JavaScript 中以循环开头的 JSON?

javascript - 过滤对象数组并设置状态数组变量

javascript - JS .map 函数不显示任何元素

javascript - undefined variable react 教程

javascript - 错误 : SyntaxError: Unexpected end of JSON input when using fetch()

reactjs - 如何在 React 应用程序中模拟 linux 终端

javascript - JSON 中第 6 位的意外标记 i - React redux 应用程序

javascript - Angularjs JSON Unicode 字符

java - 谷歌云端点返回 java long 作为 JSON 中的字符串

json - 具有对象和整数的 Swift 4 可编码数组