状态返回空数组

Jib*_*mas 7 reactjs react-hooks

我试图从 useState 钩子访问状态,但即使在我修改它之后它也给了我初始状态。

const quotesURL = "https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json";


function QuoteGenerator() {
  const [quotes, setQuotes] = useState([]);
  const [currentQuote, setCurrentQuote] = useState({ quote: "", author: "" });

  useEffect(() => {
    axios(quotesURL)
      .then(result => {
        console.log(result);
        setQuotes(result.data);
      })
      .then(() => {

        console.log(quotes);
      });
    }, []);

Run Code Online (Sandbox Code Playgroud)

console.log(quotes) 返回空数组而不是对象数组

cbd*_*per 10

以下是您应该如何做:

const quotesURL = "https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json";


function QuoteGenerator() {
  const [quotes, setQuotes] = useState([]);
  const [currentQuote, setCurrentQuote] = useState({ quote: "", author: "" });

  useEffect(() => {         // THIS WILL RUN ONLY AFTER YOUR 1ST RENDER
    axios(quotesURL)
      .then(result => {
        console.log(result);
        setQuotes(result.data);  // HERE YOU SET quotes AND IT WILL TRIGGER A NEW RENDER
      })
    }, []);                 // BECAUSE YOU'VE SET IT WITH '[]'

  useEffect(() => {         // THIS WILL RUN WHEN THERE'S A CHANGE IN 'quotes'
     if (quotes.length) {
       setSomeOtherState();   // YOU CAN USE IT TO SET SOME OTHER STATE
     }
  },[quotes]);

}
Run Code Online (Sandbox Code Playgroud)

此代码的工作原理:

  • 第一次渲染:您只是初始状态。useEffects还没有运行。
  • 第一次渲染后:两种效果都将运行(按该顺序)。第一个将触发 axios 请求。第二个什么都不做,因为quotes还没有length
  • 爱可信请求完成:then条款将运行,并且setQuotes将被调用来设置新quotes值。这将触发重新渲染。
  • 第二次渲染:现在quotes状态已更新为新值。
  • 在第二次渲染之后:只有第二次useEffect会运行,因为它正在“监听”quotes刚刚改变的变量的变化。然后你可以用它来像你说的那样设置一些状态。