使用React和Flask。创建一个网站,python从第三方api获取数据,然后显示在页面上。
我有一个问题与我的渲染,第一次页面加载,API返回json和json得到正确呈现与我的元素。如果我按f5,页面刷新,API再次被调用(我可以看到新数据被检索),但数据只是作为纯json放在屏幕上,而不是在我的元素中呈现。
chooseStash.js
const handleSubmit = async (event) => {
event.preventDefault();
const selectedStashIds = [];
sortedGroupKeys.forEach((key) => {
const stashes = groupedStashes[key];
stashes.forEach((stash) => {
if (document.getElementById(stash.id).checked) {
selectedStashIds.push(stash.id);
}
});
});
const response = await fetch('/stashIDs', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ stashIDs: selectedStashIds }),
});
if (response.ok) {
history.push('/DisplayItems');
} else {
console.error('Failed to store stash IDs:', response.statusText);
}
};
这里用户在页面上选择并点击提交按钮,这将向我的flask文件发送一些数据
api在我的flask文件中获得数据发送,并存储与StashIDs = data.get(' StashIDs ')
@app.route('/stashIDs', methods=['POST'])
def storeStashIDs():
'''
Stores the user selected stash IDs in a session variable
This is used to pull the stash content in the next endpoint
'''
data = request.get_json()
logger.info(f'[data = request.get_json()] : {data}')
stashIDs = data.get('stashIDs')
session['stashIDs'] = stashIDs
logger.info(f'[StashIDs] : {stashIDs}')
return 'Data received store stash id', 200
当用户点击提交并且数据被发送到flask时,我们被重定向到/DisplayItems
useEffect(() => {
const fetchStashContent = async () => {
const response = await fetch('/DisplayItems');
const data = await response.json();
console.log("Fetched data:", data);
const items = processStashContentData(data);
console.log("Setting items:", items);
setItems(items);
setIsLoading(false);
};
fetchStashContent();
}, []);
其中,用户第一次被定向到这个页面,/DisplayItems API(下面)被调用,并拉回一堆数据,然后相应地呈现…
@app.route('/DisplayItems', methods=['GET', 'POST'])
def returnStashContent():
'''
Returns the stash content to the frontend
'''
headers = session.get('headers')
league = session.get('league')
stashIDs = session.get('stashIDs')
logger.info(f'[stashIDs] : {stashIDs}')
stashContent = initializeGetData.pullStashData(userSelectedStashList=stashIDs,poeLeague=league,headers=headers)
return jsonify({'stashContent':stashContent})
然而,当我在这个屏幕上按f5时,我可以看到一个新的API调用发生了,然后数据被发送到屏幕,而没有通过我的元素呈现,也没有控制台。从useEffect
触发日志如果能帮助我了解情况,我将不胜感激。
我已经在api中添加了日志记录,可以看到它正在被调用我在js中添加了日志记录,可以看到当我按f5时它没有被调用(但这是用户第一次进入页面)
我试着玩了一下useEffect,但是我没有取得任何进展
return (
<div
className={`item-card ${itemType[item.frameType]}`}
key={item.id}
>
<div className={`card-title ${itemType[item.frameType]}`}>
{item.baseType.includes("Flask")
? item.typeLine
: `${item.name} ${item.typeLine}`}{" "}
</div>
<div className="item-content">
<div className="item-icon">
<img src={item.icon} alt={item.baseType} />
</div>
<div className="item-info-container">
<div className="item-info item-stats-font">
{item.frameType !== 4 &&
item.frameType !== 5 &&
item.frameType !== 6 && (
<>
<ul className="level">Item Level: {item.ilvl}</ul>
{item.ilvl && (
<div
className={`separator ${
itemType[item.frameType]
} ilvl`}
></div>
)}{" "}
</>
)}
{item.baseType.includes("Cluster Jewel") && (
<>
<ul className="enchantMods">
{item.enchantMods &&
item.enchantMods.map((mod) => (
<li key={mod}>{mod}</li>
))}
</ul>
<div
className={`separator ${
itemType[item.frameType]
}`}
></div>
</>
)}
<ul className="properties">
{processedProperties.map((property) => (
<li key={property.name}>{property.displayValue}</li>
))}{" "}
</ul>
{processedProperties.length > 0 && (
<div
className={`separator ${
itemType[item.frameType]
}`}
></div>
)}
<div className="requirements">
{item.requirements && (
<span>
Requires:{" "}
{item.requirements
.map(
(requirement) =>
`${
requirement.name
} ${requirement.values.map((v) => v[0])}`
)
.join(", ")}{" "}
</span>
)}{" "}
</div>
{item.requirements && (
<div
className={`separator ${itemType[item.frameType]}`}
></div>
)}
<ul className="implicitMods">
{item.implicitMods &&
item.implicitMods.map((mod) => (
<li key={mod}>{mod}</li>
))}{" "}
</ul>
{item.implicitMods && (
<div
className={`separator ${itemType[item.frameType]}`}
></div>
)}
{item.frameType !== 6 && (
<ul className="explicitMods">
{item.explicitMods &&
item.explicitMods.map((mod) => (
<li key={mod}>{mod}</li>
))}{" "}
</ul>
)}
{item.explicitMods && item.frameType !== 6 && (
<div
className={`separator ${
itemType[item.frameType]
} explici`}
></div>
)}
{item.frameType === 4 &&
item.hybrid &&
item.hybrid.isVaalGem && (
<>
<div
className={`separator ${
itemType[item.frameType]
}`}
></div>
<ul className="hybrid-properties">
{item.hybrid.properties &&
item.hybrid.properties.map((property) => (
<li key={property.name}>
{property.displayMode === 3
? property.name.replace(
"{0}",
property.values[0][0]
)
: `${
property.name
}: ${property.values.map(
(v) => v[0]
)}`}{" "}
</li>
))}{" "}
</ul>
<div
className={`separator ${
itemType[item.frameType]
}`}
></div>
<ul className="hybrid-explicitMods">
{item.hybrid.explicitMods &&
item.hybrid.explicitMods.map((mod) => (
<li key={mod}>{mod}</li>
))}{" "}
</ul>
</>
)}
{!item.identified && (
<div className="unidentified">Unidentified</div>
)}
{item.corrupted && (
<div className="corrupted">Corrupted</div>
)}
<div className="influences">
{item.influences &&
Object.keys(item.influences)
.filter((influence) => item.influences[influence])
.map((influence, index) => (
<div
key={index}
className={`influence-${influence}`}
>
{capitalizeFirstLetter(influence)}{" "}
</div>
))}{" "}
</div>
<div className="stash-name">
Stash: {item.stashName}{" "}
</div>
</div>
</div>
</div>
</div>
);
调用handlessubmit的代码
<Form className="mainStashBox" method="POST" style={{ width: '100%', height: '80%' }} onSubmit={handleSubmit}>
我设法解决了它…
由于该页的url是/DisplayItems, api端点也是/DisplayItems,这似乎导致了一些问题…