有什么方法可以从不同的组件触发React.useEffect吗



想象一下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行进行更改。状态正在改变,但不知何故,我无法在第一个组件中触发React.useEffect,即使很难。它与[myState]有关。为什么?

简而言之,我的问题是:;useEffect triggered";当我在输入中进行更改时,在我的控制台上

不应向MyComponent2提供myStatesetMyState,而应仅提供setMyState并使用函数更新参数来访问当前状态。

handleChange函数中,您当前正在更改React状态(直接修改(:

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

相反,您应该将状态设置为数组(其对象标识与当前数组不同(:

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]);

最新更新