为什么我的图像和信息不在我的 React 本地主机上渲染?



最近我开始了一门React课程,该课程的目标是创建一个怪物式的网站。下面我将留下相关JS和JSX文件的代码。我的SearchBox输入确实出现在我的屏幕上,但是,具有各自h2和p的怪物图像并不只出现在我的react localhost中。我试着通过我的代码来理解为什么我的代码不工作,我还没能找到一个解决方案。在这里,我将把链接留给我从哪里获得图像的API,你只需要改变之前的数字?访问其他图像。我知道,类是有点过时的,由于挂钩,但课程最初是专注于他们,这样我们就可以理解他们的行为,所以请不要更新代码,只是帮助我的功能。

https://robohash.org/1?set=set2&大小= 180 x180

App.js文件
import React, {Component} from 'react';
import './App.css';
import { CardList } from './components/card-list/card-list';
import {SearchBox} from './components/search-box/search-box';

class App extends Component {
constructor() {
super();
this.state = {
monsters: [], 
searchField: ''
};
} 
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => this.setState({monsters: users}));
}
render() {
const {monsters, searchField} = this.state;
const filteredMonsters = monsters.filter(monster => monster.name.toLowerCase().includes(searchField.toLowerCase())) //This checks if one of the monsters name includes the text inputted into the search field, and filters out those that do not. We lower case it to avoid capital and lower case issues.
return (
<div className='App'>
<SearchBox 
placeholder='Search Monsters'
handleChange={e => this.setState({searchField: e.target.value})}
/>
<CardList monsters={filteredMonsters}/> 
</div> //By using filteredMonsters here, initially all will appear but as we place some input, only those that include the searchField will appear
)
}
};

export default App;

卡。jsx文件

import React from 'react';
export const Card = props => {
return (
<div>
<img src={'https://robohash.org/'+ props.monster.id + '?set=set2&size=180x180'} alt='monster'/>
<h2> {props.monster.name} </h2>
<p> {props.monster.email} </p>
</div>
) 
}

贺卡名单。jsx文件

import React from 'react';
import { Card} from '../card/card';
import './card-list.css';
export const CardList = props => {
return (
<div className='card-list'>
{props.monsters.map((monster) => {
<Card key={monster.id}/>
})}
</div>
)
};

CardList中,您甚至从未将monster对象传递给Card组件。只有一个怪物id作为钥匙。基本上,您需要这样的内容:

<div className='card-list'>
{props.monsters.map((monster) => {
<Card key={monster.id} monster={monster} />
})}
</div>

次要建议:对Card组分进行适当的解构:

export const Card = ({ monster: { id, name, email } }) => {
return (
<div>
<img src={'https://robohash.org/'+ id + '?set=set2&size=180x180'} alt='monster'/>
<h2> {name} </h2>
<p> {email} </p>
</div>
) 
}

工作沙盒:https://codesandbox.io/s/fervent-cerf-qcubt?file=/src/App.js

相关内容

  • 没有找到相关文章

最新更新