2016-03-08 45 views
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> 
    ); 
    } 

} 

這是處理通過這個數據的最佳方式?如果是這樣,我如何在我的組件的渲染方法中訪問這些數據?

謝謝!

回答

2

將其存儲在組件狀態中。渲染方法應當僅依賴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: {}} 
    } 
} 
+3

在設置狀態之前,最有可能需要JSON.parse()內容。 –

相關問題