Javascript 如何从React中的全局变量设置状态数组
我试图将状态变量设置为componentWillMount中全局变量的值 我根据用户的兴趣(使用forEach函数)进行API调用,并尝试将结果存储在全局变量中,后者将其存储在状态变量中(用户:{articles}) 由于某些原因,在呈现中,Javascript 如何从React中的全局变量设置状态数组,javascript,reactjs,api,asynchronous,Javascript,Reactjs,Api,Asynchronous,我试图将状态变量设置为componentWillMount中全局变量的值 我根据用户的兴趣(使用forEach函数)进行API调用,并尝试将结果存储在全局变量中,后者将其存储在状态变量中(用户:{articles}) 由于某些原因,在呈现中,this.state.user.articles变量始终为空。我错过什么了吗 下面是我如何设置初始值的: class Home extends Component { constructor(props){ super(props);
this.state.user.articles
变量始终为空。我错过什么了吗
下面是我如何设置初始值的:
class Home extends Component {
constructor(props){
super(props);
this.state = {
user :{
articles: [],
}
}
this.componentWillMount.bind(this);
}
这里是我调用API并尝试使用this.setState
更新变量的地方
async componentWillMount(){
const loggedUser = await Auth.currentAuthenticatedUser();
const userEntry = await API.get(apiName,path + loggedUser.username);
console.log(userEntry)
currentInterests = userEntry.userInterests;
currentInterests.forEach(async function (interest) {
console.log(interest);
let query = 'q='+interest+'&';
let url = 'https://newsapi.org/v2/everything?' +
query +
'from=2019-02-22&' +
'sortBy=popularity&' +
'apiKey=hiddenforsecurity';
let req = new Request(url);
const response = await fetch(req);
const json = await response.json();
console.log(typeof json.articles);
for(var key in json.articles){
results.push(json.articles[key])
}
console.log(results[15]);
});
this.setState({
user : {
articles: results,
}
})
}
虽然console.log(results[15])
返回预期的元素,但在呈现console.log(this.state.user.articles)
中
render() {
console.log(this.state.user.articles)
return (
<ul>
{this.state.user.articles.map((article, index) => {
console.log(article.author)
return (<li key={index}>{article.author}</li>)})}
</ul>
);
}
来自组件的willmount无效。我错过了什么?我在网上尝试了无数次修复,但似乎什么都不起作用 主要问题是,
forEach
不会等待每个回调运行。在下面的示例中,done
将在数组元素之前打印(thing1
,thing2
,thing3
)。
const things=[“thing1”、“thing2”、“thing3];
//https://gist.github.com/eteeselink/81314282c95cd692ea1d
const delay=ms=>newpromise(resolve=>setTimeout(resolve,ms));
const exampleFunction=async()=>{
things.forEach(异步(thing)=>{
等待延迟(500);
console.log(东西);
});
控制台日志(“完成”);
}
exampleFunction()代码>setState
在forEach
完成之前被调用,下面是一个简单的说明:
const arr=[1,2,3,4,5];
arr.forEach(异步e=>{
常数a=等待取数('https://jsonplaceholder.typicode.com/todos/1')
.then(response=>response.json())
控制台日志(a)
})
log('after the loop')
Yes,这就解决了它。谢谢。我不确定是否可以在forEach函数中使用异步函数。将forEach更改为正常值以解决此问题。很高兴听到。如果这完全解决了您的问题,那么您可以将此答案或使用良好的承诺的其他答案标记为公认的答案。对于所有方法,我可以给您一些建议1。在componentDidMount中使用API调用,2。const loggedUser=wait Auth.currentAuthenticatedUser();const userEntry=await API.get(apiName,path+loggedUser.username);您可以将这些调用添加到componentDidMount并设置为状态Q。为什么您需要在componentWillMount中使用async Wait?因为API调用是异步的,而且我以前使用过componentDidMount,但没有任何效果。您是否尝试使用一些模型值设置数组(在componentWillMount中)?类似于[{author:'a'},{author:'b'},{author:'c'}]
的东西,然后看看它是否按照您的意愿呈现?顺便说一句,您应该改为ComponentDidMount
,因为WillMount one现在不推荐使用。如果循环方法不需要绑定,那么,componentWillMount
也不推荐使用。改用componentDidMount
this.setState({
user : {
articles: results,
}
})