简体   繁体   中英

React - Set property of a component from another Component

I am complete noob to react so please bear with me.

I am creating a webpage that has dusting on react components on it. I am not creating the whole page using react and this isn't an option.

What i want I want to do is load a json file and use the data to set the properties of the components on the page. These properties won't be changing once the page has rendered.

I have managed to load the json and set the properties of a component. I also need to reuse some of the properties of this component in other components that are not a children of the first component.

I suppose very basically I need to create a global set of data that can be used by any component on the page. I'm coming from an angular background so maybe this is throwing me off course a bit

Here is what I have so far

    var ReleaseList=React.createClass({

      getInitialState: function(){
        return {
          allReleases:[]
        }
      },
      showResults :function(ReleaseData){

        this.setState({
          allReleases :ReleaseData
        });
      },

      getReleases:function(){
        fetch('http://imac.local:5757/s0dj8a.json').then(function(response) {
            // Convert to JSON
            return response.json();
            }).then(function(j) {
                var ReleaseData=j.releaseDetail[0]
                this.showResults(ReleaseData)
            }.bind(this));
      },
      componentDidMount(){
        this.getReleases();
      },

      render:function(){
    return (

            <h1>{this.state.allReleases.title}</h1>
      )

      }
    });

    var ReleaseDataTitle=React.createClass({
      render:function(){
    return (
      <div>
              <h2>{this.props.title}</h2>
              // This needs to be the same as this.state.allReleases.title in the previous component

      </div>
      )
      }

      });

    ReactDOM.render(<ReleaseList/>, document.getElementById('content'));
    ReactDOM.render(<ReleaseDataTitle title={'I need this to be the same as this.state.allReleases.title in <ReleaseList />'}/>, document.getElementById('banner'));

I wouldn't consider React to render small static parts of your website just as I wouldn't use jQuery if I know JS well - it's unnecessary download for such a simple task. I would however consider Preact , a 3kb React clone that was made for these kind of situations: small parts of site / app with similar API.

But here's how I would do it with React (I imagine Preact is very similar).


These properties won't be changing once the page has rendered.

If the data doesn't change, you don't even need to store the data to global variable, just render React components while passing the fetched data as props .

fetch('http://imac.local:5757/s0dj8a.json').then(function(response) {
    return response.json()
}).then(function(data) {

     ReactDOM.render(<First data={data} />, document.getElementById('first'))
     ReactDOM.render(<Second data={data} />, document.getElementById('second'))

     // And any other React component you wish to add to DOM

})

Now the data is available in each of these components as this.props.data . Now you can do whatever you want with this data: format, change, pass to children, render etc .

PS! Me and even React creators recommend to use ES6 classes, especially if you just started ..

The key is something you've already mentioned in your question. You need a global state where you can store the data required by your components. You will also need some methods to do the data distribution.

For the sake of easy maintenance, predictability and reliability of our apps, I believe React components should be agnostic about data (which means they should only represent the View layer, and shouldn't handle API calls or data processing by themselves).

Since your website is not completely built with react, you can delegate vanilla javascript methods for data fetch and pass it as a props to your React components. If you ever plan to fully migrate to React, you can make use of Redux , MobX , etc. to maintain your global state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM