【问题标题】:displaying array in component populated by Axios get request在由 Axios 获取请求填充的组件中显示数组
【发布时间】:2018-11-01 17:08:45
【问题描述】:

我有一个 react 组件,它使用 Axios 从 API 获取一堆照片。

可以,但是现在不知道如何在组件中显示图片。

如何使用照片数组并将它们显示在我的组件中?

下面是axios返回的数组截图:

这是我的组件:

class ImagePlayer extends Component {

componentDidMount() {
    axios.get(`/api/gameRPG/monsterImages/${this.props.encounterId}/pics`)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });

}
render() {
    return (
        <div>
            <div>Show Encounter Pics</div>
            <div></div>
        </div>
    );
}
}

export default ImagePlayer;

谢谢!

【问题讨论】:

    标签: reactjs axios react-component


    【解决方案1】:

    您可以将响应数据存储到组件的状态中:

    this.setState({photos: response.data})
    

    然后在render方法中使用组件的状态:

    this.state.photos.map((photo) => ...some render logic here...)
    

    如果您正在构建某种更大的/生产应用程序,我建议将数据从本地组件的状态外部化到状态容器(redux)并使用中间件查询后端(在您的组件中不直接调用 axios)。

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多