当两件事发生变化时反应触发器useEffect

时间:2019-05-25 08:06:07

标签: reactjs

我正在尝试使用react钩子,并且我想在有两件事发生变化时运行一个函数:

const Filter = ({ orderList, orders }) => {
  const [from, setFrom] = useState();
  const [to, setTo] = useState();
  const [filteredList, setFilteredList] = useState(orders);

  useEffect(() => {
    const filteredOrders = orders.filter(function(item) {
      return item.order_number >= from && item.order_number <= to;
    });
    setFilteredList(filteredOrders);
    console.log(filteredList);
  }, [from, to]);

更准确地说,我只想同时更改fromto的状态时过滤数组,这是因为我试图从用户定义的某些输入中过滤数组。

我该如何实现?

1 个答案:

答案 0 :(得分:0)

默认情况下,只要更改一项,您将无法通过向useEffect()传递更多参数来完成此操作,这将导致useEffect执行。

不过,您可以将useRefuseRef结合使用以完成此操作。我们将使用const App = () => { const [from, setFrom] = useState(); const [to, setTo] = useState(); const previousValues = useRef({ from, to }); useEffect(() => { if ( previousValues.current.from !== from && previousValues.current.to !== to ) { //your logic here console.log("both changed") previousValues.current = { from, to }; } }); return ( <div> <input placeholder="from" value={from} onChange={e => setFrom(e.target.value)} /> <input placeholder="to" value={to} onChange={e => setTo(e.target.value)} /> </div> ); }; 存储状态的先前值,并将其与新的状态值进行比较。

例如参见codeandbox:https://codesandbox.io/s/heuristic-nobel-6ece5

application-settings