如何延迟来自 useContext 的数据

时间:2021-05-21 14:29:33

标签: reactjs react-hooks

我的代码没有设置 boarditems 的状态,因为无论何时调用 useEffect,currentUser 都是 null。如何在调用 useEffect 之前等待检索 currentUser?

  const [boarditems, setboarditems] = useState([]); 
  const currentUser = useContext(CurrentUserContext); 

  useEffect(() => {
    if (currentUser) {
      const items = []; 
      db.collection("boarditems")
    .where("userID", "==", currentUser.id)
    .get()
    .then(query => {
      query.forEach(doc => {
        items.push({
          id: doc.id, 
          ...doc.data()
        })
      })
      setboarditems(items);
    })
  }
  }, [])

1 个答案:

答案 0 :(得分:1)

const path = require('path'); const htmlWebpack = require('html-webpack-plugin'); const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); const isDevelopment = process.env.NODE_ENV !== 'production'; module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, devServer: { port: 3000, host: '0.0.0.0', disableHostCheck: true, useLocalIp: true, open: true, hot: true, }, mode: isDevelopment ? 'development' : 'production', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: require.resolve('babel-loader'), options: { plugins: [ isDevelopment && require.resolve('react-refresh/babel') && '@babel/plugin-syntax-nullish-coalescing-operator', ].filter(Boolean), }, }, }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, resolve: { extensions: ['.js', '.jsx'], }, plugins: [ new htmlWebpack({ template: './src/index.html', }), isDevelopment && new ReactRefreshWebpackPlugin(), ].filter(Boolean), }; 添加到 currentUser 的依赖项数组。每当上下文发生变化时,组件都会重新渲染,如果 useEffect() 自上次重新渲染后发生变化,并且不是 currentUser,则将进行调用:

null