【问题标题】:How can I create a List of items from the API data I get?如何从我获得的 API 数据创建项目列表?
【发布时间】:2019-09-22 13:39:55
【问题描述】:

我正在尝试创建从 API 获取的子类别列表并将它们显示在应用程序中。问题是我不知道如何将 Array (API) 中的项目转换为 List 项目。

componentDidMount(){
      axios.get('/categories/' + this.props.match.params.id)
          .then(response => {
              console.log(response.data.children) //Array of strings

          }) 
  }

 render(){

      return(
          <div className={classes.Showcategory}>
              <h1>{this.props.match.params.id}</h1>
              <li>Here I need for each string of the array a list item<li/>
          </div>
      );
  }

【问题讨论】:

  • 将响应存储在由状态管理的数组中,然后使用Array.map返回它。

标签: javascript reactjs api axios


【解决方案1】:

您可以为组件定义一个状态变量。当您发出请求时,更新状态。当状态得到更新时,您的组件将使用您想要的数据重新呈现。

试试这个:

constructor(props) {
  super(props);

  this.state = {
    categories: []
  };
}

componentDidMount() {
  axios.get("/categories/" + this.props.match.params.id).then(response => {
    console.log(response.data.children); //Array of strings
    this.setState({ categories: response.data.children });
  });
}

render() {
  return (
    <div className={classes.Showcategory}>
      <h1>{this.props.match.params.id}</h1>
      {this.state.categories.map((category, index) => (
        <li key={index}>{category}</li>
      ))}
    </div>
  );
}

请注意React recommends that you don't use index as the key。对于您的情况,如果 category 字符串是唯一的,请改用它们。

【讨论】:

    猜你喜欢
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多