使用 axios.get 渲染 json 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40870919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:43:34  来源:igfitidea点击:

Rendering json data with axios.get

jsonreactjsaxios

提问by NDeveloper

I am new to react.js and I am trying to fetch server side data in JSON format in a table. So what I did is:

我是 react.js 的新手,我试图在表中以 JSON 格式获取服务器端数据。所以我所做的是:

export default class TableUser extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    table: [],
  }
}
componentDidMount(){
  axios.get('http://www.reddit.com/r/reactjs.json')
    .then((response)=>{
      const table = response.data.map(obj => obj.data);
        this.setState({ table });
      })
    .catch((err)=>{

    })
}

And I am rendering this in a <div>like:

我把它渲染成<div>这样:

render(){
    <div><p>{this.state.table.kind}</p></div>
}

why I am not getting the value for kind? Please suggest!!

为什么我没有得到 的价值kind?请推荐!!

回答by Alexander T.

obj.data(in datathere is property childrenwhich is Array) is Objectnot Array, I think in this case better change default state, and create one field for kind(String) and one for data(Array), like so

obj.data(在data有物业childrenArray)是Object不是Array,我觉得在这种情况下,更好地改变默认状态,创造一个字段kindString),一个用于dataArray),像这样

class TableUser extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      kind: '',
      data: []
    };
  }
  
  componentDidMount(){
    axios
      .get('https://www.reddit.com/r/reactjs.json')
      .then(({ data })=> {
       this.setState({ 
          kind: data.kind, 
          data: data.data.children
        });
      })
      .catch((err)=> {})
  }
      
  render() {
    const child = this.state.data.map((el, index) => {
      return <div key={index}>
        <p>Title - { el.data.title }</p>
        <p>Author - { el.data.author }</p>
      </div>
    });

    return <div>
      <p>{ this.state.kind }</p>
      <div>{ child }</div>
    </div>;
  }
}

ReactDOM.render(
  <TableUser />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.js"></script>
<div id="container"></div>