代码之家  ›  专栏  ›  技术社区  ›  Leem.fin

关于使用useffect钩子的几个问题

  •  0
  • Leem.fin  · 技术社区  · 4 年前

    我是新来的本地人和钩子。在我的react原生项目中,我需要查询一个屏幕 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 总是在运行 使用效果 代码?

    2. 你可以看到 processedData 在useffect中返回,如何将该返回传递到布局代码以呈现处理过的数据?

    0 回复  |  直到 4 年前
        1
  •  1
  •   Philip Feldmann    4 年前

    第一个问题: 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
    

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

    第二个问题: 你只能通过使用 useState 在效果中设置状态:

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