简体   繁体   English

如何在不重新渲染组件的情况下更改 useState 的状态,而只是重新渲染其组件

[英]How to change useState's state without re-rendering the component, but just its components

How do I change the useState without re-rendering it but just its components?如何更改 useState 而不重新渲染它,而只是它的组件? Why I need is because I have some logic that changes the useState in Comp1.为什么我需要是因为我有一些逻辑可以改变 Comp1 中的 useState。 If I would re-render Comp1 I would have to recalculate its value.如果我要重新渲染 Comp1,我将不得不重新计算它的值。 But if the change happens I still would like to re-render its components.但是如果发生变化,我仍然想重新渲染它的组件。

Edit: bigger code snippet.编辑:更大的代码片段。

function Comp1() {
  const [user, setUser] = useState({});

  firebase.auth().onAuthStateChanged(function (_user) {
    if (_user) {
      // User is signed in.
      setUser(_user);
    } else {
      setUser({ exists: false });
    }
  });

  return (
    <div>
      <UserProvider.Provider value={{user, setUser}}>
        <Comp2 />
        <Comp3 />
      </UserProvider.Provider>

    </div>
  );
}

function Comp2(props) {
  const { user, setUser } = useContext(UserProvider);
  return (
    <div>
      {user.exists}
    </div>
  )
}

function Comp3(props) {
  const { user, setUser } = useContext(UserProvider);
  return (
    <div>
      {user.exists}
    </div>
  )
}

//User Provider

import React from 'react';

const UserProvider = React.createContext();
export default UserProvider;

I took a shot at answering your question.我试着回答你的问题。 Basically, you want to be able to calculate a value once and have it updated only when the content changes.基本上,您希望能够计算一次值并仅在内容更改时更新它。 You can do this with useEffect .你可以用useEffect做到这一点。 The first parameter for useEffect is a function you want to happen on mount/update. useEffect的第一个参数是您希望在挂载/更新时发生的函数。 It should return a function to run when your function is unmounted (if any).当您的函数被卸载(如果有)时,它应该返回一个要运行的函数。 The second argument are the things that determine if useEffect gets ran.第二个参数是决定useEffect是否运行的东西。 I put it to run when user changes value.user更改值时,我将其运行。 Hopefully this is enough to get you started down the path of something.希望这足以让你开始走上这条路。 You can read more about useEffect in the docs .您可以在文档中阅读有关useEffect的更多信息。

function Comp2(props) {
  const { user, setUser } = useContext(UserProvider);
  const { state, setState } = useState({ value: '' });

  useEffect(() => {
    console.log(user);
    // perform expensive operation
    setValue({ value: 'My expensive operation is now stored' });
    return () => {
      // Do you have anything that you would put in componentWillUnmount()?
      // Put that here
    };
  }, [user]);

 console.log(state.value);

  return (
    <div>
      {user.exists}
    </div>
  )
}

我的建议是放弃 useContext钩子,因为它们似乎会导致重新渲染它们所附加的组件。

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

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