【发布时间】:2022-01-21 11:04:13
【问题描述】:
我正在从 json 中获取数据。我想在我的 React 组件中显示该数据。但是每次我尝试将从 json 返回的对象传递给我的状态时,它只返回一个并删除前一个,而不是 json 中的整个元素。
这是我的代码。
const [state, setState] = useState({});
const connection = new Connection("devnet");
const { publicKey } = useWallet();
useEffect(() => {
(async () => {
//if not public key, close
if(!publicKey) return;
//get tokens
let response = await connection.getTokenAccountsByOwner(
publicKey!, // owner here
{
programId: TOKEN_PROGRAM_ID,
}
);
response.value.forEach((e) => {
const accountInfo = SPLToken.AccountLayout.decode(e.account.data);
//get only tokens with value of 1
if ( parseInt(`${SPLToken.u64.fromBuffer(accountInfo.amount)}`) === 1 ) {
const tokenPublicKey = `${new PublicKey(accountInfo.mint)}`
//get the metadata of each NFT
const run = async () => {
const ownedMetadata = await programs.metadata.Metadata.load(connection, await programs.metadata.Metadata.getPDA(tokenPublicKey));
//get only tokens of the collection ...
if (ownedMetadata.data.updateAuthority === "Address_authority") {
//show the json data from arweave
let url= ownedMetadata.data.data.uri;
fetch(url)
.then(res => res.json())
.then((out) => {
setState(prevState => {
// THIS IS NOT WORKING FOR ME :(
return {...prevState, ...out};
});
})
.catch(err => { throw err });
}
};
run();
}
});
})()
}, [connection, publicKey]);
console.log(state)
【问题讨论】:
-
可能不相关,但这可能是一堆不同的状态变化(尽管
response.value中有许多元素)。你可能想要完成所有的获取,然后更新一次状态。 -
还要注意
.catch(err => { throw err })没有做任何有用的事情。
标签: reactjs json use-state solana