React js组件,如何添加json feed

时间:2018-04-08 10:35:16

标签: javascript reactjs react-router react-redux components

我尝试创建反应组件,将feed URL作为props接受,然后显示数据。 在代码中: LeageMatch的1-LeagueInfo子组件。 2-LeageMatch父组件它是主要组件,我将feed传递给LeaguInfo(它的孩子)作为index.js中的道具

`

/////LeagueInfo-Child compnent////
import React, { Component } from 'react';
class LeagueInfo extends Component{
    constructor(props){
        super(props);
        this.state = {
            error: null,
            isLoading : false,
            league : '',
            feed : this.props.feed
        }
        this.apiUrl = process.env.REACT_APP_API_URL;
        console.log(this.apiUrl);
         this.API =this.apiUrl+this.state.feed+".json"    

    }
    componentDidMount(){
     // const API =this.apiUrl+this.state.feed+".json"  ???      
        this.setState({ isLoading: true });
        fetch(this.API,{
            method: 'get',
            dataType: 'json',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            }
          })
          .then((response) => response.json())
          .then(data=>{
             let  league = <p> <img src={"feedurl"+(data.competitionId)+".png"} /> {data.competitionName}</p>;
              
              this.setState({league: league});
          })
          .catch(error => this.setState({ error, isLoading: false }));
    }
    render(){
        return(
            <h2>
           {this.state.league}
           </h2>
        );
    }
}

export default LeagueInfo;

/////LeageMatch-Parent compnent////
import React, { Component } from 'react';
import LeagueInfo from './LeagueInfo'



class LeagueMatch extends Component {
  constructor(props){
    super(props);
    this.state = {};
  }
  render() {
    return (
        <LeagueInfo feed={this.props.leagueInfofeed} />
    ...);
    }
 }
}

export default LeagueMatch;

//index.js
const LeagueMatchWrapper = document.getElementById('leaguematch-wrapper');
ReactDOM.render(<LeagueMatch  leagueInfofeed="league"/>, LeagueMatchWrapper);

` 在代码中 我有新的反应,所以有一些问题:

  1. 这是将Feed添加到组件的正确方法。
  2. 我应该将Feed添加到组件的状态feed : this.props.feed
  3. 如果我将componentDidMount()中的feed API声明为:const API =this.apiUrl+this.state.feed+".json"当组件首先呈现时它显示正确的数据然后它隐藏它,我能知道为什么吗?
  4. 如果Feed更新后反应会自动重新渲染组件,或者我必须添加一些lister

0 个答案:

没有答案