简体   繁体   English

如何使 React 功能组件重新创建回调 function 并读取更新的道具

[英]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.

相关问题 如何在 React 功能组件中添加 Redux function 作为带有 Props 的参数 - How to Add Redux function as a Parameter with Props in React Functional Component 如何在 React Functional Component 中为 setState 创建指定的回调函数 - How to create a specified callback function for a setState in React Functional Component 如何在 React 功能组件中正确更新 props - How to update props correctly in React functional component 如何在React的功能组件中制作与componentDidUpdate函数类似的函数? - How to make a similar function as componentDidUpdate function in a functional component in React? 反应功能组件类型错误:无法读取未定义的属性“道具” - React functional component TypeError: Cannot read property 'props' of undefined React组件的props如何异步更新? - How is React component's props updated asynchronously? 功能组件中的构造函数(道具)反应 - constructor(props) in functional component react 功能组件未在反应中接收道具 - Functional Component not receiving props in react 反应:如何访问 class 组件中的功能组件的道具 - React: How can I acces to props of a functional component in a class component Typescript/React 功能组件的道具 function - 什么类型? - Typescript/React functional component's props function - what type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM