繁体   English   中英

有没有办法从不同的组件触发 React.useEffect ?

[英]Is there any way to trigger React.useEffect from different component?

想象一下 React 中有两个这样的组件:

import MyComponent2 from "./components/MyComponent2";
import React from "react";

export default function App() {
  const [myState, setMyState] = React.useState([]);

  React.useEffect(() => {
    console.log("useEffect triggered");
  }, [myState]);

  return <MyComponent2 myState={myState} setMyState={setMyState} />;
}
import React from "react";

export default function MyComponent2(props) {
  const [inputValue, setInputValue] = React.useState("");

  function handleChange(e) {
    setInputValue(e.target.value);
    let list = props.myState;
    list.push(`${e.target.value}`);
    props.setMyState(list);

    console.log(props.myState);
  }

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        name="text"
        onChange={handleChange}
      />
    </div>
  );
}

如您所见,我正在使用第二个组件中的 props.setMyState 行进行更改。 State 正在发生变化,但不知何故我无法在第一个组件中触发 React.useEffect 甚至很难它与 [myState] 连接。 为什么?

简而言之,我的问题是:当我更改输入时,我无法在控制台上触发“useEffect”

不应将myStatesetMyState提供给MyComponent2 ,而应仅提供setMyState并使用功能更新参数来访问当前的 state。

在您的handleChange function 中,您当前正在改变 React state ( 直接修改它):

let list = props.myState; // This is an array that is state managed by React
list.push(`${e.target.value}`); // Here, you mutate it by appending a new element
props.setMyState(list);
// ^ You update the state with the same array here,
// and since they have the same object identity (they are the same array),
// no update occurs in the parent component

相反,您应该将 state 设置为数组(其 object 标识与当前数组不同):

props.setMyState(list => {
  const newList = [...list];
  newList.push(e.target.value);
  return newList;
});

// A concise way to write the above is like this:
// props.setMyState(list => [...list, e.target.value]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM