P粉8059224372023-08-16 15:36:35
const [todos, setTodos] = useState<string[]>([]);
and
const renderItem = useCallback( () => { //todo's here is a closure, it will not update //a dependency of [] means, just run once. }, [] );
This is a common problem because it's not obvious. Because this happens often, setState
has a callback version. In your code you are actually using it to set the state, but you also need to use it to get the current state for a maximum of 10 checks.
So a simple solution is to put the length check in the callback function of useState.
setTodos((curr) => curr.length >= 10 ? curr : [item.name, ...curr]);
In the above code, if the current length is greater than or equal to 10, only the current status is returned, otherwise a new item is added.
Another option, of course, is to add todos to useCallback's state, but why this doesn't work in FlashList
, not sure.
A better option is to extract Item
as another child component. There are other benefits to doing this, such as more composability, code sharing, and most importantly, performance.