将useStatesetter传递给孩子以更新父母状态是正确的方法吗?

我们可以将回调作为道具传递给孩子并更新状态,但我只是想知道我是否可以将 useState setter 传递给孩子并直接在孩子中调用它来更新父母状态?

就像是:

function Parent(){
  const [data, setData] = useState();
  
  return(
    <Child setData={setData}/>
  );
}

function Child({setData}){
  useEffect(()=>{
    setData('new data'); //Calling setter here to update
  }, [])
}

回答

是的,你可以这样做。事实上,这样做是一种很好的做法。为了避免不必要的重新呈现和无限循环,无论是包括setData孩子的依赖性阵列中useEffect或包裹data在一个useCallback在父组件。此外,建议在使用时将数据初始化为某个初始值useState。在你的情况下,我会将它初始化为null->const [data, setData] = useState(null)

依赖数组的示例:


function Child({ setData }) {
  useEffect(() => {
    setData("new data"); //Calling setter here to update
  }, [setData]);

  return (...);
}

如果你想把它传递给一个多层次的孩子,我建议使用 Context. 有了上下文,然后你可以使用useState任何的孩子,你不需要把它作为贯穿于所有的孩子们的道具ParentChild要在使用它。

上下文示例:


// Step 1. Create context
const MyContext = React.createContext();

// Step 2. Create a custom hook that will return Context
// This will allow you to use the context in any number of children more easily.
// And it will also make sure that it is only used within Parent component
const useData = () => {
  const context = React.useContext(MyContext);

  if (!context) {
    throw new Error("useData must be used within a <Parent />");
  }

  return context;
};

function Parent() {
  const [data, setData] = useState(null);
  const value = [data, setData];

  // Step 3. Use Context Provider and pass the value of the props that
  // need to be used by any children down the tree
  return (
    <MyContext.Provider value={value}>
      <Child />
    </MyContext.Provider>
  );
}

function Child() {
  return <ChildTwo />;
}

function ChildTwo() {
  // Step 4. Extract the prop from the Context that you need using custom hook
  const [data, setData] = useData();

  useEffect(() => {
    setData("new data"); //Calling setter here to update
  }, [setData]);

  return (...);
}


以上是将useStatesetter传递给孩子以更新父母状态是正确的方法吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>