【问题标题】:map function is not iterating the state objects(in array format) in react.jsmap 函数没有在 react.js 中迭代状态对象(数组格式)
【发布时间】:2021-07-08 12:24:31
【问题描述】:

我正在 react.js 中构建一个 iTunes 搜索项目,它在其中获取输入字段中输入的名称的音乐专辑数据。我正在使用 iTunes 搜索 api 来获取数据,数据为 json 格式,每个搜索包含 50 个对象。

我从 api 获得的数据以数组格式存储/设置为数据状态(我使用钩子来存储数据对象)。

这里我通过setData([json.results[0]])获取每个对象的数据

但问题是 map 函数无法遍历数据状态数组。

我已经尝试了所有方法,但 map 函数没有迭代数据状态对象。 而且它也没有给出任何错误。

谁能告诉我为什么它不起作用? 提前致谢。

这里是代码。

import { useState } from "react"
const Search = () => {
    const [name, setName] = useState(null);
    const [data, setData] = useState([]);

    const handleInput = event => {
        setName(event.target.value);
    };

    const getIdata = async () => {

        let url = "https://itunes.apple.com/search?term=" + name;
        let cors = "https://cors-anywhere.herokuapp.com/";
        
        setData([]);

        fetch(url)
            .then(data => data.json())
            .then(json => {
                setData([json.results])
            })

        console.log(data);
   }

    return (
        <>
            <div>
                <h1>iTunes App</h1>
                <div>
                    <p>Search: <input className="input-field col s6" id="daal" onChange={handleInput} /></p>
                    <button onClick={getIdata} id="btn">submit</button>
                </div>
                <div className="row" id="output"></div>
            </div>



            {

                data.map(curr => {
                    return (
                        <>
                            <h1>{curr.artistName}</h1>
                            {<div className="row" id="output">
                                <div className="col s4 m4 l4">
                                    <div className="card">
                                        <div className="card-image waves-effect waves-block waves-light">
                                            <img className="activator" src={curr.artworkUrl100} />
                                        </div>
                                        <div className="card-content">
                                            <span className="card-title activator grey-text text-darken-4">{curr.artistName}<i
                                                className="material-icons right">more_vert</i></span>
                                            <p><a href="#">This is a link</a></p>
                                        </div>
                                        <div className="card-reveal">
                                            <span className="card-title grey-text text-darken-4">{curr.trackCensoredName}<i
                                                className="material-icons right">close</i></span>
                                            <p>Here is some more information about this product that is only revealed once clicked on.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>}
                        </>
                    );
                })
            }
        </>
    )
}

export default Search

【问题讨论】:

  • 不要在setData([]) 中使用另一个setData([json.results])then 中。另外,在发送请求之前和之后,当您在 render 方法中 console.log(data) 时会看到什么?
  • 是的,我从代码中删除了setData([])。当我在请求之前console.log(data) 时我什么都没有得到,而在请求之后我得到了对象。
  • 什么样的对象?为了使用map,它需要是一个数组。

标签: javascript json reactjs dictionary state


【解决方案1】:

您正在将一个数组放入带有setData([json.results]) 的数组中,并且data 设置为:

[[ { «song» }, { «song» }, { «song» } ]]

注意双重[[]]。直接设置获取的歌曲列表,而不是将其包装在另一个数组中。例如。 setData(json.results) 这应该导致 data 是:

[ { «song» }, { «song» }, { «song» } ]

目前没有错误的原因是因为您只能访问像 curr.artistName 这样的对象属性,如果 curr 是一个数组,它就可以正常工作。

const curr = [];
curr.artistName //=> undefined (no error)

如果您尝试对结果值执行任何操作并且不希望它是undefined,您将收到错误消息。例如curr.artistName.split("") 会抛出一个错误,因为你不能在undefined 上调用split

【讨论】:

  • 非常感谢您的解决方案和令人惊叹的解释!?
猜你喜欢
  • 2020-10-05
  • 2021-06-05
  • 1970-01-01
  • 2021-12-31
  • 2019-05-24
  • 2017-06-23
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
相关资源
最近更新 更多