【问题标题】:React items.map is not a function when items is an array?当 items 是数组时,React items.map 不是函数?
【发布时间】:2019-12-16 19:15:17
【问题描述】:

加载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;

【问题讨论】:

    标签: javascript json reactjs api


    【解决方案1】:

    您的实际数据来自json.results,因此您需要将json.results 设置为类似状态,

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

    你需要像这样迭代数组,

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

    Demo

    【讨论】:

    • 查看演示。
    猜你喜欢
    • 2019-04-21
    • 2019-08-03
    • 2022-01-25
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多