簡體   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