【问题标题】:State variable shows value 'undefined' though have set default value 'false'状态变量显示值“未定义”,但已设置默认值“假”
【发布时间】:2020-12-23 16:50:18
【问题描述】:

我创建了一个自定义组件MyCustomList,它只是FlatList 的包装。共有三个道具itemsgetMoreloading。这篇文章只关注传入的 loading 属性。

const MyCustomList = ({items, getMore, loading}) => {
      // console shows 'false'
      console.log(loading) 
      
      // use the 'loading' as the default value for the state variable
      const [isLoading, setIsLoading] = useState(loading);

      const myFooter = () => {
           // console shows undefined, why? Shouldn't it be the default value 'false'?
           console.log(isLoading});
            ...
      }
      return (
          <FlatList
            keyExtractor={keyExtractor}
            data={items}
            renderItem={renderItem}
            onEndReached={getMore}
            onEndReachedThreshold={0}
            ListFooterComponent={myFooter}
    />
  );
  ...
  export default MyCustomList;
}

在上面的自定义组件中,父组件传入 loading 属性,值为 false,在运行时将列表滑动到底部时,会调用 myFooter 但状态变量 isLoading 会记录值为 undefined .为什么?

【问题讨论】:

    标签: reactjs react-native use-state react-state-management


    【解决方案1】:

    只改成这个

    const MyCustomList = ({items, getMore, loading = false}) => {
    

    ....

    【讨论】:

      【解决方案2】:

      如下更改您的代码,我们将isLoading 状态设置为useEffect

       import React, { useState, useEffect } from 'react';//add
       
       const MyCustomList = ({items, getMore, loading}) => {
                 // console shows 'false'
                 console.log(loading) 
                 
                 // use the 'loading' as the default value for the state variable
                 const [isLoading, setIsLoading] = useState(loading);
           
                 useEffect(() => {
                   setIsLoading(loading)
                  }, []);
       
                 const myFooter = () => {
                      // console shows undefined, why? Shouldn't it be the default value 'false'?
                      console.log(isLoading});
                       ...
                 }
                 return (
                     <FlatList
                       keyExtractor={keyExtractor}
                       data={items}
                       renderItem={renderItem}
                       onEndReached={getMore}
                       onEndReachedThreshold={0}
                       ListFooterComponent={myFooter}
               />
             );
             ...
             export default MyCustomList;
           }
      

      【讨论】:

        猜你喜欢
        • 2018-08-06
        • 2021-11-28
        • 1970-01-01
        • 2018-10-18
        • 1970-01-01
        • 2012-09-06
        • 2013-10-01
        • 1970-01-01
        • 2019-09-10
        相关资源
        最近更新 更多