首页 > 解决方案 > 在 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>

标签: reactjsaxios

解决方案


React 规则规定,在对状态对象进行更改时,必须使用 setState。在你的情况下,这将是

if (res.data.length > 0) {
  return setLive([...live, res.data.data])
}

在收到 api 结果之前可能会触发 console.log(live)。尝试将 console.log(live) 包装在 setTimeout 中以确认这一点。


推荐阅读