【问题标题】:Issue getting API to render in react问题让 API 在反应中呈现
【发布时间】:2020-03-23 12:45:17
【问题描述】:

我正在尝试从我找到的 API Here 中获取要显示的图像,但我在控制台中收到以下错误..

Fetch API 错误:TypeError: this.state.dogs.map is not a function

代码如下:

<html>
    <head>
        <title>ICS 211 - React</title>
        <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script crossorigin src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
        <script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
        <meta charset="utf-8"></meta>

        <!-- google font -->
        <link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet">

        <style>
                html {
                    background-color: #f8f8f8;
                    font-family: 'Roboto', sans-serif;
                }
        </style>
    </head>
    <body>

        <div id="container"></div>
        <script type="text/babel">

            class AppClassStateful extends React.Component {
                constructor(props) {
                    super(props);
                    this.state = { dogs: [] };
                };

                componentDidMount() {
                    (async () => {
                        try {
                            const response = await fetch('https://dog.ceo/api/breeds/image/random');
                            if (!response.ok) throw Error(response.status + ': ' + response.statusText);    
                            const data = await response.json();
                            this.setState({ dogs: data })
                        } catch(error) {
                            console.log('Fetch API error: ' + error);
                        }
                    }) ();
                }

                render() {
                    return (
                        <div>
                        <StyledTitle />
                            <ol>
                                {this.state.dogs.map(dog => <StyledDog key={dog.id} link={dog.message}/>)}
                            </ol>
                        </div>
                    );
                }
            }

            const Title = ({ className }) => {
                return (
                    <div className={ className }>
                        <h1>Pictures of Dogs</h1>
                        <h3>Greg Paul Simmons</h3>
                    </div>
                    );
                }

            const Dog = ({className, message}) => {
                return <img src={message} alt="Picture of dog"/>
            }

            const StyledTitle = styled(Title)`
                font-size: 50pt;
                font-family: sans-serif;
                color: #FFF;
                background: #e3d8aa;`;

            const StyledDog = styled(Dog)`
                font-family: "Arial", sans-serif;`;


            ReactDOM.render(
            <AppClassStateful/>,
            document.getElementById('container')
            );
        </script>
    </body>


</html>

如果有人能指出我正确的方向,我将不胜感激。在这一点上,我完全被卡住了。

谢谢

【问题讨论】:

标签: javascript html reactjs state


【解决方案1】:

在此处定义const data = await response.json() 时,数据是客观响应。您必须访问 keydata 才能从 API 获取结果

此外,URL https://dog.ceo/api/breeds/image/random,只返回一个图像,而不是数组图像。您可以使用 URL https://dog.ceo/api/breed/hound/afghan/images 来获取图像数组:

(async () => {
    try {
        const response = await fetch('https://dog.ceo/api/breed/hound/afghan/images');
        if (!response.ok) throw Error(response.status + ': ' + response.statusText);    
        const data = await response.json();
            this.setState({ dogs: data.message }) 
            // access to message to get an array of images
        } catch(error) {
            console.log('Fetch API error: ' + error);
        }
}) ();

在组件内部使用地图操作符

return (
    <div>
        <StyledTitle />
        <ol>
             {this.state.dogs.map((dog, key)=> 
                  // dog here as a link
                  <StyledDog key={key} link={dog}/>
             )}
        </ol>
    </div>
);

【讨论】:

    【解决方案2】:

    map 是 JavaScript 数组原型的函数。如果 API 响应不是数组类型,则它没有 map 函数。

    如果您更改代码以保留“dogs”数组并仅将 API 响应推送给它,它应该可以工作:

    this.setState({ dogs: this.state.dogs.concat(data) })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多