反应JSON渲染猫图像

时间:2019-12-12 09:19:10

标签: javascript html reactjs

我似乎无法让我的React项目正常工作。我正在尝试创建一个将显示随机猫图像的应用程序,我在此处https://aws.random.cat/meow

中包含了代码和api链接

如果有人可以帮助我弄清楚如何使它工作,我会予以纠正,我想我的问题出在我的地图功能上。我是使用React的新手,正在尝试了解更多信息。谢谢

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<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>
		<script type="text/babel">
			
			class Application extends React.Component {

				constructor(props) {
					//super is calling the constructor from react component
					super(props);
					//seting the state
					this.state = { cats: [] };
				};
				//we want to fetch the api and take the value it returns and set it equal to data
				componentDidMount() {
					(async () => {
						try {
							//change
							const response = await fetch('https://aws.random.cat/meow');
							if (!response.ok) throw Error(response.status + ': ' + response.statusText);
							const data = await response.json();
							//change
							this.setState({ cats: data });
						}catch(error){
							console.log('Fetch API Error: ' + error);
						}
					}) ();
				}
				
				render() {
					return (
						<div>
						
						<StyledTitle />
							<ol>
								{this.state.cats.map(cat => <StyledApplication key={cat.file}/>)}
							</ol>
						</div>
					);
				}
			}
	
			
		
			//structure and style for the Title object
			const Title = ({ className }) => (
				<div className={className}>
					<h1>random cats</h1>
				
				</div>
			);

			const StyledApplication = styled(Application)`
			background-color: white;
			padding: 15px;
			color: lightgreen;`;

			const StyledTitle = styled(Title)`
			font-size: 45pt;
			font-family: sans-serif;
			color: #6699ff;
			padding: 3%;
			border: solid green 2px;
			background: lightgreen;`;
			
	
			
			//structure and style for the Movie object
			// link,name,checked is the json object
			const struct = ({ className, file }) => {

					return <li className={className}>{className}: <a href={file}>{file}</a></li>
			
			};
			



			ReactDOM.render(
				<Application/>,
				document.getElementById('container')
			);
		</script>
	</head>
	<body>
		<div id="container"></div>
	</body>
</html>

3 个答案:

答案 0 :(得分:1)

这里有一些技巧可以解决您的问题

  1. 使用扩展运算符将元素推到CATS数组中

您已将cats初始化为一个数组,并且为了将响应中返回的数据推入,请使用像这样的传播运算符

this.setState({ cats: [...data] });

  1. 地图功能中缺少返回关键字

您必须指定这样的地图函数返回的内容

{this.state.cats.map(cat => return <StyledApplication key={cat.file}/>)}

此外,如果您检查传递的迭代器,则地图函数为cats 但是在道具key中,您通过了cat.item,您需要像我上面一样纠正它。

  1. 使用AXIOS(可选)

为了发出网络请求,请使用axios软件包。 Axios使向REST端点发送异步HTTP请求变得容易

希望这会有所帮助

答案 1 :(得分:0)

API返回了一个对象,并且map函数用于数组。您应该执行以下操作:

state = {
    cat: null
}

render() {
    const { cat }= this.state;
    return (
        <div>
             <StyledApplication key={cat.file}/>
        </div>
    )
}

如果要对象数组,请执行以下操作

state = {
    cats: []
}

componentDidMount() {
    ...
    const { cats } = this.state;
    // Clone the array because of immutability 
    const copy = cats.map(c => {...c});
    copy.push(data);
    this.setState({ cats: copy });
    ...
}

render() {
    const { cat }= this.state;
    return (
        <div>
             <StyledApplication key={cat.file}/>
        </div>
    )
}

答案 2 :(得分:0)

无论您做什么,都是正确的,但是您的api响应是我可以看到的对象。您正在尝试遍历该对象。因此,它不起作用。更改api响应或格式化api响应数据并将其设置为数组。

相关问题