如何更新功能组件中的 flatlist 数组 [extraData 不起作用]
How to update flatlist arrays in functional component [extraData won't work]
删除数组对象后,我希望 flatlist 能够更新,但它失败了,直到我重新加载应用程序。有没有办法实时获取更新?
我的代码:
...imports...
arr = [
{id:1, name:'test1'},
{id:2, name:'test2'},
{id:3, name:'test3'},
]
export default function App() {
const [posts, setPosts] = useState([])
setTimeout(() => { delBet() }, 8000)
function delBet() {
try {
arr.splice(arr[2], 1); setPosts(arr)
//only remove {id:3, name:'test3'},
console.log(arr) //works well
//only show [{id:1, name:'test1'},{id:2, name:'test2'}]
} catch (e) { console.log(e) }
}
return (
<FlatList
data={posts}
extraData={posts} //doesn't work/make any difference
renderItem={({ item }) =>
<Post
post={item}
/>
}
/>
)
}
如果有任何帮助(包括改进我的代码),我将不胜感激
posts的实际值是[],如果你需要尝试用arr值初始化posts,就像这样:
const [posts, setPosts] = useState(arr)
此外,您可以在渲染效果中使用 setTimeout 一次。
useEffect(()=> {
setTimeout(() => { delBet() }, 8000)
function delBet() {
try {
setPosts(() => arr.splice(arr[2], 1))
} catch (e) { console.log(e) }
}
}, [])
你的状态变了,
尝试
setPosts([...arr]);
而不是 setPosts(arr);
删除数组对象后,我希望 flatlist 能够更新,但它失败了,直到我重新加载应用程序。有没有办法实时获取更新?
我的代码:
...imports...
arr = [
{id:1, name:'test1'},
{id:2, name:'test2'},
{id:3, name:'test3'},
]
export default function App() {
const [posts, setPosts] = useState([])
setTimeout(() => { delBet() }, 8000)
function delBet() {
try {
arr.splice(arr[2], 1); setPosts(arr)
//only remove {id:3, name:'test3'},
console.log(arr) //works well
//only show [{id:1, name:'test1'},{id:2, name:'test2'}]
} catch (e) { console.log(e) }
}
return (
<FlatList
data={posts}
extraData={posts} //doesn't work/make any difference
renderItem={({ item }) =>
<Post
post={item}
/>
}
/>
)
}
如果有任何帮助(包括改进我的代码),我将不胜感激
posts的实际值是[],如果你需要尝试用arr值初始化posts,就像这样:
const [posts, setPosts] = useState(arr)
此外,您可以在渲染效果中使用 setTimeout 一次。
useEffect(()=> {
setTimeout(() => { delBet() }, 8000)
function delBet() {
try {
setPosts(() => arr.splice(arr[2], 1))
} catch (e) { console.log(e) }
}
}, [])
你的状态变了,
尝试
setPosts([...arr]);
而不是 setPosts(arr);