I have a very simple functional component in React. When this component is rendered by the parent component, initially myList is an empty array, and then eventually when it finishes loading, it is a list with a bunch of items.
The problem is, the value of myList inside onSearchHandler never gets updated, it's always [].
const MyComponent = ({ myList }) => { const [filteredList, setFilteredList] = useState(myList); console.log(myList); // <<< This outputs [], and later [{}, {}, {}] which is expected. useEffect(() => { setFilteredList(myList); }, [myList]); const onSearchHandler = (searchText) => { console.log(myList); /// <<< When this function is called, this always outputs [] const filteredItems = myList.filter(item => item.name.toLowerCase().includes(searchText.toLowerCase()) ); setFilteredList(filteredItems); }; return <AnotherComponent items={filteredList} onSearch={onSearchHandler} /> }; Is there a way to force onSearchHandler to re-evaluate the value of myList? What would be the recommended approach for this sort of operation?
https://stackoverflow.com/questions/66773749/how-to-make-react-functional-component-recreate-callback-function-and-read-updat March 24, 2021 at 10:03AM
没有评论:
发表评论