我有一个来自脚本标记的 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.state
和 this.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/