2
我有一個腳本標記JSON對象,像這樣:如何訪問React組件中的JSON?
<script type="text/json" id="json-data">
{'someData': 'Lorem ipsum...'}
</script>
我希望能拉這一信息,並在我的渲染方法的陣營組件中使用它。
這個問題似乎是,我需要這個範圍內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>
);
}
}
這是處理通過這個數據的最佳方式?如果是這樣,我如何在我的組件的渲染方法中訪問這些數據?
謝謝!
在設置狀態之前,最有可能需要JSON.parse()內容。 –