嗨,我只是想渲染一组包含新闻文章的段落。我正在使用内联样式方法创建对象,然后使用style属性将其值分配给<h2>
标签。
import React, {useState, useEffect } from 'react';
const App = () => {
//inLineStyles
const useStyle = {
backgroundColor: "#282c34",
color: "white",
padding: "40px",
fontFamily: "Arial",
textAlign: "center",
};
//State
const [news, setNews] = useState([]);
const [searchQuery, setSearchQuery] = useState("")
const [url, setUrl] = useState("http://hn.algolia.com/api/v1/search?query=Hacker")
const [loading, setLoading] = useState(false);
//APIcall
const fetchNews = () => {
setLoading(true);
fetch(url)
.then(responce => responce.json())
.then(data => (setNews(data.hits), setLoading(false)))
.catch(error => console.log(error))
}
useEffect(() => {
fetchNews();
}, [url])
const handleChange = (e) => {
setSearchQuery(e.target.value)
}
const handleSubmit = e => {
e.preventDefault()
setUrl(`http://hn.algolia.com/api/v1/search?query=${searchQuery}`)
}
const handleLoading = () => {
if (loading) {
return <h2> Loading...</h2>
}
else {
return
}
}
return (
<div>
<h1 style={useStyle}>News </h1>
{ handleLoading() }
<form onSubmit={handleSubmit}>
<input type='text' value={searchQuery} onChange={handleChange}/>
<button>Search</button>
</form>
{news.map((n, i) => (
<p key={i}> {n.title} </p>
))}
</div>
);
}
export default App;
能否让我知道为什么不应用样式? 谢谢!
答案 0 :(得分:0)
我被困在这半天了。我终于能够弄清楚。我要做的就是刷新浏览器中的页面(我正在代码编辑器中保存和编译代码,并且由于某种原因,它没有更新网页)。如果有人知道为什么会发生这种情况,请在这里对此进行评论。
感谢所有回复!