React .map不是函数
我正在尝试学习React,并且是Java的初学者。现在,我正在开发一个从Flickr的API提取数据的应用程序。问题是,当我尝试在Main.js组件中的props上使用map方法时,出现错误消息“
Uncaught
TypeError:this.props.photos.map不是函数”。在此处在Stackoverflow上搜索后,我认为问题在于this.props是javascript对象而不是数组。问题是我不知道如何使它成为一个数组。谁能解释我在做什么错?
我的代码:
class App extends Component {  constructor() {
  super();
  this.state = {
  }
}
componentDidMount() {
let apiKey = 'xxxxxxxxxxxxxxxxxx';
let searchKeyword = 'nature';
let url = `https://api.flickr.com/services/ 
           rest/?api_key=${apiKey}&method=flickr.photos.
           search&format=json&nojsoncallback=1&&per_page=50
           &page=1&text=${searchKeyword}`;
fetch(url)
  .then(response => response.json())
  .then(data => data.photos.photo.map((x) => {
    this.setState({
      farm: x.farm,
      id: x.id,
      secret: x.secret,
      server: x.server})
   // console.log(this.state)
  }))
 }
    render() {
      return (
        <div className="App">
          <Header />
          <Main img={this.state.photos} />
          <Navigation />
        </div>
      );
    }
  }
  export default class Main extends Component {
  render() {
    return(
      <main className="main">
        {console.log(this.props.photos)}
      </main>
    )
  }
 }
编辑:为什么this.props.img首先未定义?
从console.log(this.props.img)截屏
回答:
fetch(url)  .then(response => response.json())
  .then(data => data.photos.photo.map((x) => {
    this.setState({
      farm: x.farm,
      id: x.id,
      secret: x.secret,
      server: x.server})
  }))
发生的情况是,您的诺言中的地图功能正在为返回的每张照片重置组件的状态。因此,您的状态将始终是返回的照片列表中的最后一个对象。
这是我所指的更简化的示例
const testArray = [1,2,3,4];let currentState;
testArray.map((value) => currentState = value)
console.log(currentState);
你想做的就是这个
const testArray = [1,2,3,4];let currentState;
//Notice we are using the return value of the map function itself.
currentState = testArray.map((value) => value)
console.log(currentState);
对于要完成的工作,您希望状态是map函数的结果(因为它从map中返回结果数组)。像这样:
fetch(url)  .then(response => response.json())
  .then(data => 
    this.setState({
      photos:
        data.photos.photo.map((x) => ({
          farm: x.farm,
          id: x.id,
          secret: x.secret,
          server: x.server
        }))
     })
   )
以上是 React .map不是函数 的全部内容, 来源链接: utcz.com/qa/405208.html

