我試圖根據一個JSON物件的串列來創建一些元素,就像這樣:
{Object}。
{Object.entries(this. state.topTen).forEach(([name]) => /span> {
console.log(name); //this correctly print the list of names。
React.createElement(MyCustomComponent, {name: name})。
})}
我還嘗試了在回圈內使用以下方法:
<MyCustomComponentname={name} />
但是我沒有看到螢屏上有任何渲染,我確定this.state.topTen有正確的資訊,因為回圈中的console.log顯示的是正確的資訊。而如果我在回圈外添加一個<MyCustomComponentname={name} />,該組件就能正確呈現。
uj5u.com熱心網友回復:
方法.forEach()將不會回傳任何東西。
你將需要使用陣列的.map()方法并回傳React.createElement(MyCustomComponent, {name: name});的結果。
例如:
{Object.entries(this. state.topTen).map(([name]/span>) => {
console.log(name); //this correctly print the list of names。
return React.createElement(MyCustomComponent, {name: name})。
})}
使用.map()將回傳一個陣列,其中包含你在回呼中回傳的任何專案。這個陣列可以被React渲染,因為回呼將回傳React.createElement(...)的結果。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
uj5u.com熱心網友回復:
我完全同意Bradon建議的答案,而且最好將陣列中的關鍵道具傳遞給子組件,這將提高應用程式在重新渲染時的性能,也能消除意外問題。 https://reactjs.org/docs/lists-and-keys.html通過該鏈接以獲得更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326341.html
標籤:
下一篇:我是否正確包裹了文本元素?
