我正在使用React Web App,并且试图循环对象列表并将内容输出到另一个挂钩,有关详细信息,请参见下文。
我面临的问题是当我循环对象时,我只会得到一个结果。
Object.keys(transactions).forEach((key, index) =>
{output = <TransactionsItem name={transactions[key].lable} />}
)
当我尝试连接时,它不起作用。
Object.keys(transactions).forEach((key, index) =>
{output = output + <TransactionsItem name={transactions[key].lable} />}
)
如何连接?
所需的完整信息
transactionsList挂钩
const Transactions = () =>{
var [user, setUser] = useContext(UserContext);
function TransactionList(props){
var output
transactions = props.user.transactions
Object.keys(transactions).forEach((key, index) =>
{output = <TransactionsItem name={transactions[key].lable} />}
)
return(output);
}
return(
<div>
<Menu />
<TransactionList user={user} />
</Grid>
</div>
</div>
)
}
TransactionList
const TransactionsItem = (props) => {
return(
<div>{props.name}</div>
);
}
对象
{
-LqaBL5jD3ktq_duQNH2: {amount: 5, date: "07/10/2019, 23:28:37", lable: "coffee"},
-LqaBLZlT_zGjr9pngWE: {amount: 5, date: "07/10/2019, 23:28:39", lable: "coffee"},
-LqaBLqKtdbp15PGdwDs: {amount: 10, date: "07/10/2019, 23:28:40", lable: "Ride"},
-LqaBM9QiHwUtmNgHN5P: {amount: 10, date: "07/10/2019, 23:28:41", lable: "Lunch"},
-LqfCNGS-4fRbgTZFnn6: {amount: 10, date: "08/10/2019, 22:51:14", lable: "Ride"},
-LqfCONTvk5p0MfK2tGc: {amount: 10, date: "08/10/2019, 22:51:18", lable: "Ride"},
-LqfCOjq1lO9auOnka1S: {amount: 10, date: "08/10/2019, 22:51:20", lable: "Ride"},
}
答案 0 :(得分:2)
使用javascript映射而不是forEach
function TransactionList(props){
var output
transactions = props.user.transactions
output = Object.keys(transactions).map((key, index) => <TransactionsItem name={transactions[key].lable} />)
return(output);
}
希望以上方法都能奏效。
答案 1 :(得分:0)
得到一个结果的原因是因为output = ...
仅将最后一个分量分配给输出变量。 Javascript中对象的串联应使用数组方法完成。为简洁起见,最好使用Gangadhar的解决方案,但是如果您不熟悉Array.map
方法,则应该更容易阅读:
function TransactionList(props) {
var output = []
var transactions = props.user.transactions
Object.keys(transactions).forEach((key) =>
{ output.push(<TransactionsItem name={transactions[key].lable} />) }
)
return output
}
答案 2 :(得分:0)
import React, { useState } from "react";
function App() {
const [list, setList] = useState(" ");
const [items, updateOnClick] = useState([ ]);
function updateList(event) {
const valueEntered = event.target.value;
setList(valueEntered);
}
function updateClick(){
updateOnClick(list);
}
return (
<input onChange={updateList} type="text" value={list} />
<button onClick={updateClick}>
<span>Add</span>
</button>
<div>
<ul>
{items.map(item => <li>{item}</li>) }
</ul>
</div>);}
export default App;