Reactjs 使用React显示从REST API返回的数据时出现问题
我正在试用一些东西,在前端使用react chatbot工具包,并从RESTAPI获取数据。Console.log显示了里面的数据。但是,当试图在调用函数的控制台上输出数据时,我得到了错误“UncaughtTypeError:无法读取未定义的属性'map'。我需要帮助在函数handleAppIList()的console.log中显示返回的数据。提前谢谢 PS:我当然是React的新手:),因为我不清楚如何处理异步完成的RESTAPI调用。期待着解决这个问题。任何关于解决此问题的帮助和提示都将不胜感激 代码如下:Reactjs 使用React显示从REST API返回的数据时出现问题,reactjs,restapi,Reactjs,Restapi,我正在试用一些东西,在前端使用react chatbot工具包,并从RESTAPI获取数据。Console.log显示了里面的数据。但是,当试图在调用函数的控制台上输出数据时,我得到了错误“UncaughtTypeError:无法读取未定义的属性'map'。我需要帮助在函数handleAppIList()的console.log中显示返回的数据。提前谢谢 PS:我当然是React的新手:),因为我不清楚如何处理异步完成的RESTAPI调用。期待着解决这个问题。任何关于解决此问题的帮助和提示都将不
// ActionProvider starter code
class ActionProvider {
constructor(createChatBotMessage, setStateFunc) {
this.createChatBotMessage = createChatBotMessage;
this.setState = setStateFunc;
this.state = {
error: null,
users: []
}
}
greet() {
const greetingMessage = this.createChatBotMessage("Hi! Greeting!")
this.updateChatbotState(greetingMessage)
}
// This is being called when the user types in 'api' in chat window
handleApiList()
{
const { error, users } = this.state;
this.getData();
if(error) {
console.log("Error: ", error.message)
}
else {
let myarray=[]
users.map(function(user)
{
myarray += `${ user.name }\n`;
return `${ user.name }`;
})
console.log(myarray)
}
}
getData()
{
console.log("in now")
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(
(result) => {
this.setState({
users: result
});
},
(error) => {
this.setState({ error });
}
)
}
handleJobList = () => {
const message = this.createChatBotMessage(
"Fantastic, I've got the following jobs available for you",
{
widget: "jobLinks",
}
);
this.updateChatbotState(message);
};
updateChatbotState(message) {
// NOTE: This function is set in the constructor, and is passed in
// from the top level Chatbot component. The setState function here
// actually manipulates the top level state of the Chatbot, so it's
// important that we make sure that we preserve the previous state.
this.setState(prevState => ({
...prevState, messages: [...prevState.messages, message]
}))
}
}
export default ActionProvider;
您正在获取getData,它是一个异步函数。数据还没有准备好。只返回数据比返回设置状态更好 代码的简化版本
handleApiList()
{
const { error, users } = this.state;
const data = await this.getData();
//data is ready, do what u want with the data here.
}
}
const getData = async() => {
return fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
)
}
.map返回一个数组,如果要推送,则需要使用forEach
范例
let myarray=[]
data.forEach((user) =>
{
myarray.push(user.name });
})
console.log(myarray)
发行说明:
const { error, users } = this.state; // gets state values
this.getData(); // updates state values
if(error) {
console.log("Error: ", error.message)
}
else {
let myarray=[]
users.map(function(user) // users is value before state update
我建议从getData()
返回带有api调用结果的承诺。之后,您可以在中的handleAppIList()
中执行代码。然后()
提议:
getData()
{
console.log("in now")
return fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(
(result) => {
this.setState({
users: result
});
return result;
}
)
}
我还会将错误处理移到.catch()
还可以看看。使用async/await而不是单纯的承诺更容易、更简洁;) 非常感谢特别的人!你真的是一个特别的人:)我从昨天起就一直在努力解决这个问题,而且成功了。在我的例子中,使用before-getData不起作用,因此被删除。还使handleApiList成为异步的,并且工作起来很有魅力。非常感谢你的帮助。感谢:)感谢您对Ogochi问题的回答。第一个答案是由一个特别的人发布的,所以我没有尝试这么做。谢谢:)