[英]How to make React functional component recreate callback function and read updated props
I have a very simple functional component in React.我在 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.当这个组件被父组件渲染时,最初的
myList
是一个空数组,最终当它加载完成时,它是一个包含一堆项目的列表。
The problem is, the value of myList
inside onSearchHandler
never gets updated, it's always []
.问题是,
myList
里面onSearchHandler
的值永远不会更新,它总是[]
。
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?有没有办法强制 onSearchHandler 重新评估 myList 的值? What would be the recommended approach for this sort of operation?
这种操作的推荐方法是什么?
It sounds like AnotherComponent
does not take into consideration the changed prop - this should be considered to be a bug in AnotherComponent
.听起来
AnotherComponent
没有考虑更改的道具 - 这应该被认为是AnotherComponent
中的错误。 Ideally, you'd fix it so that the changed prop gets used properly.理想情况下,您会修复它,以便正确使用更改后的道具。 Eg, just for an example, maybe it's doing
例如,仅举个例子,也许它正在做
const [searchHandler, setSearchHandler] = useState(props.onSearch);
and failing to observe prop changes as it should.并且未能按照应有的方式观察道具变化。 Or, for another random example, this could happen if the listener prop gets passed to an
addEventListener
when the component mounts but again doesn't get checked for changes and removed/reattached.或者,对于另一个随机示例,如果在组件安装时侦听器道具被传递给
addEventListener
但再次没有检查更改并删除/重新附加,则可能会发生这种情况。
If you can't fix AnotherComponent
, you can use a ref for myList
in addition to the prop:如果您无法修复
AnotherComponent
,您可以使用myList
除了 prop 之外的 ref:
const MyComponent = ({ myList }) => {
const myListRef = useRef(myList);
useEffect(() => {
myListRef.current = myList;
setFilteredList(myList);
}, [myList]);
const [filteredList, setFilteredList] = useState(myList);
const onSearchHandler = (searchText) => {
const filteredItems = myListRef.current.filter(item =>
item.name.toLowerCase().includes(searchText.toLowerCase())
);
setFilteredList(filteredItems);
};
It's ugly, but it might be your only option here.它很丑,但它可能是你在这里唯一的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.