簡體   English   中英

當items是數組時,React items.map不是函數嗎?

[英]React items.map is not a function when items is an array?

加載API並獲取.map不是功能。 一直在瀏覽每個示例,並嚴格按照它們進行操作,但仍然出現此錯誤。 該錯誤當然發生在ul標簽的.map

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://opentdb.com/api.php?amount=10&category=18&difficulty=easy&type=boolean"
    )
      .then(res => res.json())
      .then(json => {
        this.setState({ isLoaded: true, items: json });
      });
  }

  render() {
    var { isLoaded, items } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="App">
          <ul>
            {items.map(item => (
              <li key={item.results.question}>{item.results.question}</li>
            ))}
          </ul>
        </div>
      );
    }
  }
}

export default Login;

您的實際數據來自json.results ,因此您需要將json.results設置json.results

this.setState({ isLoaded: true, items: json.results });

您需要像這樣迭代數組,

{ items.map(item => (
     <li key={item.question}>{item.question}</li>
))}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM