繁体   English   中英

如何从类json数组中返回reactjs

[英]How to return from class 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"
}

这是你如何做到的:

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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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