【问题标题】:How to access JSON in a React Component?如何在 React 组件中访问 JSON?
【发布时间】:2016-03-08 22:04:03
【问题描述】:

我有一个来自脚本标签的 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>
    );
  }

}

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

谢谢!

【问题讨论】:

    标签: json reactjs


    【解决方案1】:

    将其存储在组件的状态中。渲染方法应该只依赖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.parse() 内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2021-08-15
    相关资源
    最近更新 更多