我希望得到的网址与类别=业务,但网络自动重置我的状态到网址,没有发送的类别。我不知道背后的原因
let {id}=useParams()
const [newsurl,setNewsurl]=useState(()=>{
const initialstate="https://newsapi.org/v2/top-headlines?country=us&apiKey=c75d8c8ba2f1470bb24817af1ed669ee"
return initialstate;})
//console.log(id);
const [articles, setActicles] = useState([]);
useEffect( ()=>{
if(id === 2)
console.log("condition")
setNewsurl("https://newsapi.org/v2/top-headlines?country=de&category=business&apiKey=c75d8c8ba2f1470bb24817af1ed669ee")},[])
useEffect(() => {
const getArticles = async () => {
const res = await Axios.get(newsurl);
setActicles(res.data.articles);
console.log(res);
};
getArticles();
}, []);
useEffect(() => {
console.log(newsurl)
// Whatever else we want to do after the state ha
s been updated.
}, [newsurl])
//return "https://newsapi.org/v2/top-headlines?country=us&apiKey=c75d8c8ba2f1470bb24817af1ed669ee";}
return (<><Newsnavbar />{articles?.map(({title,description,url,urlToImage,publishedAt,source})=>(
<NewsItem
title={title}
desciption={description}
url={url}
urlToImage={urlToImage}
publishedAt={publishedAt}
source={source.name} />
)) } </>
)
还有一件事是,当我保存代码的网页将更改为有类别,但当我刷新它,它更改回初始状态。同样的情况下,当键入的网址没有id。我可以知道如何解决这个问题和背后的原因吗?
2条答案
按热度按时间mbyulnm01#
在React中设置状态的作用类似于异步函数。
这意味着,当您设置状态并将
console.log
放在它后面时,它可能会在状态实际完成更新之前运行。例如,您可以改为使用依赖于相关状态的
useEffect
挂钩,以查看状态值是否按预期得到更新。范例:
此
console.log
将仅在状态完成更改并发生呈现后运行。请查看documentation以了解有关此问题的更多信息。
qyswt5oh2#
setState
是一个异步操作,所以在第一次渲染中,当你的url等于你传递给useState
钩子的默认值时,你的两个useEffetc
都运行。在下一次渲染中,你的url被更改,但是第二个useEffect
不再运行,因为你传递了一个空数组作为它的依赖项,所以它只运行一次。您可以像下面的代码片段那样重写代码来解决问题。