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还没有运行。quotes还没有length。then条款将运行,并且setQuotes将被调用来设置新quotes值。这将触发重新渲染。quotes状态已更新为新值。useEffect会运行,因为它正在“监听”quotes刚刚改变的变量的变化。然后你可以用它来像你说的那样设置一些状态。| 归档时间: |
|
| 查看次数: |
10016 次 |
| 最近记录: |