应用程序启动时不会显示我的数据。它只在我尝试检查页面时显示。
我正在阅读JSON数据,这些数据需要一些时间才能可用。因此,我添加了一个async/await。
如何修复代码,使其在加载时显示?
以下是我的代码片段:
const WeatherWidget = ({ id, editMode }) => {
const [roles, setRoles] = useState();
const getGoalData = async () => {
return (
[
{
"username": "user1",
"goal": "$5,000,200"
},
{
"username": "user2",
"goal": "$5,000,200"
},
{
"username": "user3",
"goal": "$4,000,199"
},
]
);
}
useEffect(() => {
const setDataRole = async () => {
var json = await getGoalData();
setRoles(json)
}
setDataRole();
}, [])
return (
<Container>
<div>
ticker from widget config
</div>
<StyledUl>
<Ticker>
{({ index }) => (
<>
{roles && roles.map(({ username, goal }, i) => (
<>
{i === 0 ? null : ','}
<StyledSpanName>
<span className="name">{username}</span>
</StyledSpanName>
<StyledSpanGoal> <span className="goal">{goal}</span></StyledSpanGoal>
</>
))
}
</>
)}
</Ticker>
</StyledUl>
</Container>
);
};
您不需要加载任何内容。数据就在代码中。从一开始就把它放在roles
中。
事实上,您甚至不需要使用useState
,因为您永远不会改变roles
状态。它可以(也可能应该(是一个常数。
const WeatherWidget = ({ id, editMode }) => {
const [roles, setRoles] = useState(
[
{
"username": "user1",
"goal": "$5,000,200"
},
{
"username": "user2",
"goal": "$5,000,200"
},
{
"username": "user3",
"goal": "$4,000,199"
},
]
);
return (
<Container>
<div>
ticker from widget config
</div>
<StyledUl>
<Ticker>
{({ index }) => (
<>
{roles && roles.map(({ username, goal }, i) => (
<>
{i === 0 ? null : ','}
<StyledSpanName>
<span className="name">{username}</span>
</StyledSpanName>
<StyledSpanGoal> <span className="goal">{goal}</span></StyledSpanGoal>
</>
))
}
</>
)}
</Ticker>
</StyledUl>
</Container>
);
};
似乎忘记了async
:
useEffect(() => {
const setDataRole = async () => { // here
var res = await getGoalData()
var data = await res.json()
setRoles(data)
}
setDataRole();
}, [])