javascript - 为什么我的页面加载项目,闪烁然后一切都消失了?
问题描述
我有这段代码可以从 API 中读取并在屏幕上显示所有信息。当我尝试访问 localhost:3000 时,我可以看到所有信息,但之后它就消失了。
不确定是否缺少某些东西,但我在控制台上收到一些警告,说:
index.js:1 警告:没想到服务器 HTML 包含一个 in 。
因为这只是一个警告我不确定它是否会导致我得到的错误,但我在控制台上没有任何其他错误......
我打开了源代码,所有信息都在那里,一切似乎都是正确的。
这是我的 index.js 代码:
const Index = (props) => (
<Layout>
<RecipeCardsLayout recipes={props.recipes} />
</Layout>
)
Index.getInitialProps = async function() {
const res = await fetch('http://localhost:8080/api/public/recipes')
const data = await res.json()
console.log(`Show data fetched. Count: ${data.length}`)
return {
recipes: data
}
}
这是我的布局代码:
const Layout = props => (
<div>
<Header />
{props.children} {/* important so Layout children will be rended */}
</div>
)
这是我的标题:
const Header = () => (
<div>
<Head>
<title>How to Keto Cook</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
</Head>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">How to Keto Cook</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav>
</div>
)
这就是我认为缺少一些东西的地方:它是 RecipeCardsLayout
class RecipeCardsLayout extends React.Component {
render() {
let rows = [];
while(this.props.recipes.length > 0){
var recipes = this.props.recipes.splice(0, 4);
let cols = [];
for(var i = 0; i < recipes.length; i++){
let col = [];
col.push(
<div class='col-sm-3'>
<RecipeCard id={recipes[i].id} name={recipes[i].name} url={recipes[i].image.url}></RecipeCard>
</div>
);
cols.push(col);
}
let row = <div class='row'>{cols}</div>;
rows.push(row);
}
return (
<div>{rows}</div>
)
}
}
如果有人能给我一个关于如何调试并找到这个错误的指导,那就太棒了。我是 React 和 Nextjs 的新手,发现调试这个有点困难,因为我在控制台上看不到任何错误。
解决方案
试试这个...
class RecipeCardsLayout extends React.Component {
render() {
return (
<div>
{
recipes.map(recipe => {
return (
<div className="row" key={recipe.id}>
<div className="col-sm-3">
<RecipeCard id={recipe.id} name={recipe.name} url={recipe.image.url} />
</div>
</div>
)
})
}
</div>
);
}
}
在该render()
方法中,正在发生的事情是我们recipes
通过调用该map
方法并返回一个包含行元素、列元素和每个配方的配方卡的节点来循环遍历数组。
请注意,我们也在使用className
而不是class
在<div>
's 上。
推荐阅读
- swift - ObjectMapper - Initialize an empty init in child class
- ios - Tabindex 属性未按预期工作(ios/osx)
- mysql - 选择 sql 中第一次出现三个唯一值的时候
- ios - Flutter 不会构建 iOS 版本 - 完成
- django - Django模板覆盖
- perl - 错误检查字符串
- c++ - 外部设备的有限状态机
- php - cURL 无法正确发送内容类型
- amazon-web-services - AWS IoT Shadow - 如何处理或拒绝无效的“期望”状态?
- c - 错误:(1098)XC8 中变量“_sprintf”的声明冲突