[英]React Native, pushing items to an array state not working
我需要將項目推送到我的數組,但是當我console.log
這個數組時,它會針對特定值顯示“未定義”。 順便說一下,我正在嘗試從 firebase 存儲中獲取數據。 如何正確地將項目添加到數組
這是我的代碼:
const [imagelinks, setImagelinks] = React.useState(['']);
const myFunction = () =>{
await storage()
.ref(`${_userid}`)
.list()
.then(result => {
result.items.forEach(async ref => {
await storage()
.ref(ref.fullPath)
.getDownloadURL()
.then(url => {
//get url
setImagelinks([...imagelinks, url]);
console.log('Links: ' + url);
});
});
//there it says undefined when logging...
console.log(imagelinks[0])
});
}
編輯:我可以使用以下嗎?
const imagelinks = [];
//instead of
const [imagelinks, setImagelinks] = useState([]);
更新state
是一個異步任務。 需要重新渲染組件才能獲得更新后的值。 可以肯定的是,在myFunction
之外添加您的控制台,例如在 state 定義下方:
const [imagelinks, setImagelinks] = React.useState(['']);
console.log(imagelinks)
如果你想使用結果來做一些邏輯(例如 API 調用),你可以使用useEffect
掛鈎,例如:
useEffect(()=>{
if(imagelinks.length>0){
// do your things, except do not call setImagelinks in here to avoid having a loop because imagelinks is in the dependencies array of useEffect.
}
},[imagelinks])
正如前面提到的答案,設置后您無法在同一個 scope 中訪問新的 state,因為它仍然具有該特定 scope 的舊值。
如果您確實需要在同一個 scope 中存儲和訪問某些值,您可以使用 useRef 鈎子,或者您可以將該值存儲在該 scope 中的一個變量中。
這是一個示例,但請記住,更改引用值不會觸發重新渲染,因此這不會替換您的 useState。
變量示例:
let imageLinksArray=[...imagelinks, url] //add this in your function
console.log(imageLinksArray) //you can pass this to the next function
使用引用示例:
const imagelinksRef = useRef() //add this on top after your useState
...
imageLinksRef.current=[...imagelinks, url] //add this in your function
console.log(imageLinksRef.current) //this will give you the result you're expecting
您還可以查看此 npm package 讓您在設置后直接通過 ref 訪問新的 state(如果您確實需要) https://www.npmjs.com/package/react-usestateref
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.