类型错误:无法读取未定义的 ReactJS API 调用的属性'map'



我最近一直在尝试使用React.js中的API,我相信下面的代码会起作用,基于https://reactjs.org/docs/faq-ajax.html,然而,当我运行此代码时,我不断得到

TypeError:无法读取未定义的属性"map">

下面是我的代码,这是一个名为DOTA的组件,并导出到我的App.js

import React from 'react';
const API_KEY ="some-api-key";
const DEFAULT_QUERY = 'redux';
class DOTA extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
info: [],
};
}
componentDidMount() {
fetch(API_KEY + DEFAULT_QUERY)
.then(response => response.json(console.log(response)))
.then((result) => {
console.log(result)    
this.setState({
isLoaded: true,
info: result.info
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}

render() {
const { error, isLoaded, info } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{this.props.info.map(item => (
<li key={ item.all_word_counts}>
</li>
))}
</ul>
);
}
}
}
export default DOTA

App.js

import React, { Component } from 'react';
import DOTA from './components/DOTA/DOTA'
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<DOTA  />
</div>
);
}
}
export default App;

我已经在这里寻找答案了,但我似乎找不到有同样问题的人。我需要在JSX之外运行.map((吗?在渲染之上?还是我只是错过了什么?

谢谢!

DOTA组件没有得到任何props,但您正在尝试map而不是this.props.info。实际上,您正在从渲染的状态顶部破坏info

这是怎么回事。info处于状态,您正在将其破坏为:

const { error, isLoaded, info } = this.state;

这从状态中获取errorisLoadedinfo,并为其分配变量。因此,您可以使用info而不是this.state.info。实际上,您正在使用error,就像if块的顶部一样。

因此,在相关部分使用它,如:

<ul>
{info.map(item => (
<li key={ item.all_word_counts}>
</li>
))}
</ul>

但是,根据您当前的代码,lis中没有任何值。我希望您现在只是在测试。

评论后更新

您的数据获取似乎存在问题。只要你有一个空的info状态,这个值就不能被定义,并且你的映射可以工作。这就是我们通常避免map of undefined错误的方法。如果我们不能有一个空状态,那么我们就进行条件渲染。

如果您想测试这个案例,只需注释掉componentDidMount方法并尝试您的代码。它有效。当然,它显示Loading,因为您没有将其设置为true。如果手动将其设置为true,则会看到一个空页面,但不会出现错误。

下面是一个使用您的代码但使用另一个fetch的工作示例:https://codesandbox.io/s/q9jx3ro7y9

因此,您应该调试fetch

最新更新