如何从类JSON Array Reactjs返回



嗨,我有此代码,该代码从文件config.json

中返回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]}}))
        }}

我在家中如何称呼它就像:home.js

<Text value="SITENAME">

所以我想这样称呼: {text.SITENAME}代替拳头一个我该怎么做?

这是JSON文件:

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

尝试以下:

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>
          )
      }
}

这是您的工作方式:

// 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]
      }
    }))
  }
}

最新更新