【问题标题】:Some questions about using the useEffect hook关于使用 useEffect 钩子的一些问题
【发布时间】:2021-03-09 19:12:53
【问题描述】:

我是 react-native 和 hooks 的新手。在我的 react-native 项目中,我有一个屏幕需要从后端查询data,那么,有一些代码使用后端返回的data 应该只在屏幕安装时运行一次。这就是我所做的(我使用react-query 从后端获取数据):

const MyScreen = ()=> {
   // fetch data from backend or cache, just think this code gets data from backend if you don't know react-query
   const {status, data, error} = useQuery(['get-my-data'], httpClient.fetchData);

   // these code only need to run once when screen mounted, that's why I use useEffect hook.
   useEffect(() => {
      // check data
      console.log(`data: ${JSON.stringify(data)}`);
      
      // a function to process data
      const processedData = processeData(data);
      
      return () => {
        console.log('Screen did unmount');
      };
   }, []);

   return (<View>
            {/* I need to show processed data here, but the processedData is scoped in useEffect hook & I need to have the process data function in useEffect since only need it to be run once */}
           </View>)
}

我的问题是:

  1. react native 是否保证useEffect 上面的代码总是在运行useEffect 代码之后总是首先被调用的顺序?

  2. 正如您所见,processedData 在 useEffect 中返回,如何将返回值传递给布局代码以呈现处理后的数据?

【问题讨论】:

  • 1 - 我认为就是这个想法,渲染块中的​​所有内容都首先发生,然后效果发生,但是您需要将 data 添加到您的数组中,否则当数据返回时,您的效果不会重新运行,因为它没有依赖项。 2 使用状态
  • 谢谢,但是in the render block 到底是什么意思?你是指return 部分还是MyScreen 开头的部分?
  • 对不起,我的意思是整个功能。 (功能组件与基于类的组件中的“渲染”功能相同

标签: react-native react-hooks use-effect


【解决方案1】:

第一个问题: useEffect 在组件完全渲染后运行,不会阻塞浏览器的绘制。考虑这个例子:

export default function App() {
  console.log("I am code from the app")
  React.useEffect(() => {
    console.log("I am the effect")
  })
  React.useLayoutEffect(() => {
    console.log("I am the layout effect")
  })
  return (
    <div className="App">
      {console.log("I am inside the jsx")}
      <h1>Hello World</h1>
    </div>
  );
}

将输出:

I am code from the app
I am inside the jsx
I am the layout effect
I am the effect

所以useEffect 回调将作为最后一件事发生,在其他所有事情都完成之后。

第二个问题:您只能通过使用useState 并在效果内设置状态来传递它:

  const [data, setData] = React.useState()
  React.useEffect(() => {
    // Your other code
    const processedData = processeData(data);
    setData(processedData)
  }, [setData])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 2019-10-02
    相关资源
    最近更新 更多