简体   繁体   English

反应 state -> h2 标签不会显示更新的 state,只是最初的一个

[英]React state -> h2 tag won't display updated state, just initial one

I have a hook state that should be displayed in a h2 tag in JSX.我有一个钩子 state 应该显示在 JSX 的 h2 标记中。 The state is updated through a fetch order. state 通过获取命令进行更新。 The thing is, the result only displays the initial values of the state, not the updated ones.问题是,结果只显示了 state 的初始值,而不是更新后的值。 By using console.log, I verified the state is indeed varying.通过使用 console.log,我验证了 state 确实在变化。 First, the state is initialized, being an array of objects with 'artist' properties.首先,初始化 state,它是一个具有“艺术家”属性的对象数组。 Artists peter and Andrew are already in the state:艺术家 peter 和 Andrew 已经在 state 中:

const [itemList, setItemList] = useState([{artist:'peter'},{artist:'andrew'}]);

I also have a button that, when clicked, orders the program to fetch an array of artists from musixmatch api through a onClick() function and update the state itemList:我还有一个按钮,单击该按钮时,命令程序通过 onClick() function 从 musixmatch api 获取艺术家数组并更新 Z9ED39E2EA931586B6A985A6942EF7 项目:

<button onClick={onClick}>Search</button>

The function onClick() code: function onClick() 代码:

const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                response.message.body.track_list.map(item => {
                let copyItemList = itemList;
                copyItemList.push({ artist: item.track.artist_name });
                setItemList(copyItemList);
            })
        });
}

The result should then be displayed in a h2 tag:然后结果应显示在 h2 标记中:

<h2>Test:{itemList.map(item => <p>{item.artist}</p>)}</h2>

As I said before, it shows only the initial artists, Peter and Andrew, but no new artists after I press the update state button.正如我之前所说,它只显示初始艺术家 Peter 和 Andrew,但在我按下更新 state 按钮后没有新艺术家。 What is the problem here, why is the new state not being shown in the h2 tag?这里有什么问题,为什么新的 state 没有显示在 h2 标签中? I wrote another function that updates the state locally, no fetch order, and it worked as intended.我写了另一个 function 在本地更新 state,没有获取顺序,它按预期工作。

The problem is that you are setting the itemlist variable once for every item inside the array you are iterating.问题是您正在为要迭代的数组中的每个项目设置一次 itemlist 变量。 You should put the setListItem outside the loop.您应该将 setListItem 放在循环之外。 Another thing is that when iterating over an array, if you are not returning any values you should use forEach instead of map.另一件事是,在遍历数组时,如果不返回任何值,则应使用 forEach 而不是 map。 Map is used when you want a return from every iteration of your loop. Map 在您希望从循环的每次迭代中返回时使用。

const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                const list = [];
                response.message.body.track_list.forEach(item => {
                list.push({ artist: item.track.artist_name });
            })
            setItemList(list);
        });
}

This will replace the old array.这将替换旧数组。 If you want to extend the initial liost, you should make a copy using the spread operator and add all the items in the list array with the same operator, like this.如果你想扩展初始的 liost,你应该使用扩展运算符进行复制,并使用相同的运算符添加列表数组中的所有项目,如下所示。

setItemList(...itemList, ...list)

If this is an array:如果这是一个数组:

response.message.body.track_list

Try尝试

setItemList([...itemList,response.message.body.track_list])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM