简体   繁体   中英

How to return from class json array reactjs

Hi i have this code that fetch and returns json data from file config.json

text.js

 class Text extends React.Component {
     constructor(props){
        super(props)
        this.state = {
          datat: [],
        };
      }
      componentDidMount(){
         fetch('/config.json')
          .then(response => response.json())
          .then((datao) =>{        
            this.setState({
                datat: (JSON.parse(JSON.stringify(datao)))
            })

          });
       }
      render(){
         const datatorender = this.state.datat;
    return ( Object.keys(datatorender).map(key =>{if(key==this.props.value){return datatorender[this.props.value]}}))
        }}

and how i call it in home is like : home.js

<Text value="SITENAME">

so i want to call it like this : {text.SITENAME} instead of fist one how can i do that ?

and this is the json file :

{
  "SITENAME": "site name",
  "SITE_DESCRIPTION":"desc"
}

Here's how you do it:

 // FILE: home.js class Home extends React.Component { constructor(props) { super(props) this.state = { datat: [], }; } render() { return <div> {this.state.datat.SITENAME === undefined ? null : this.state.datat.SITENAME} // Just like you wanted to access <Text value="SITENAME" datat={this.state.datat} updateDatat={(val) => this.setState({datat: val})}/> </div> } } // FILE: text.js class Text extends React.Component { componentDidMount() { fetch('/config.json') .then(response => response.json()) .then((datao) => { this.props.updateDatat({ JSON.parse(JSON.stringify(datao)) }) }); } render() { const datatorender = this.props.datat; return (Object.keys(datatorender).map(key => { if (key == this.props.value) { return datatorender[this.props.value] } })) } } 

Try this:

 class Text extends React.Component { constructor(props){ super(props) this.props = props; this.state = { datat: [], }; } componentDidMount(){ fetch('/config.json') .then(response => response.json()) .then((datao) =>{ this.setState({ datat: (JSON.parse(JSON.stringify(datao))) }) }); } render() { const datatorender = this.state.datat; console.log(datatorender) return ( <div> { Object.keys(datatorender).map((key, i) => { if (key === this.props.value) { return ( <li key={i}> {datatorender[this.props.value]} </li> ) } else { return null } }) } </div> ) } } 

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