reactjs - 在 Axios 请求后,我的 React 状态仍然为空
问题描述
所以我有 Axios 请求女巫需要一些特定的帐户,我希望它们填充我的 React 状态数组,但它始终保持为空
function App() {
const twitchAccounts = ["passhtet", "dallas", "bobross", "riotgames"];
const [live, setLive] = React.useState([]);
React.useEffect(() => {
for (let index = 0; index < twitchAccounts.length; index++) {
axios
.get(
`https://api.twitch.tv/helix/streams?&user_login=${twitchAccounts[index]}`
)
.then((res) => {
if (res.data.data.length > 0) {
return live.push(res.data.data);
}
})
.catch((error) => {
console.log(error);
});
}
}, []);
console.log(live, "live");
return <div />
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<div id="root" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
解决方案
React 规则规定,在对状态对象进行更改时,必须使用 setState。在你的情况下,这将是
if (res.data.length > 0) {
return setLive([...live, res.data.data])
}
在收到 api 结果之前可能会触发 console.log(live)。尝试将 console.log(live) 包装在 setTimeout 中以确认这一点。
推荐阅读
- json - 将字典转换为 JSON Swift
- javascript - Leaflet map:marker的平滑过渡不透明度变化
- gradle - 自定义 Gradle 插件 - 共享数据 beetwen 插件
- mysql - 如何使用任意数量的 OR 子句形成 Django 查询?
- python - 使用 Python 在数据框中查找对
- firebase - Flutter Firebase 存储:请求没有身份验证令牌
- c++ - 四元数乘法错误
- android - 如何使堆栈响应颤动?
- angular - 导航后Angular 8不会更改标题
- python - 如何在 PyQt 中单独显示一个对话框(没有父小部件)?