【问题标题】:Load component after api is fetched获取api后加载组件
【发布时间】:2021-07-04 08:30:59
【问题描述】:

我正在从 API 获取 json,然后我想显示组件

 const [jsonCat, setjsonCat] = useState([]);
  
 useEffect(() => {
    refreshCat();
  }, []);
    
 const refreshCat = async () => {
        try {
          console.log("refreshing categories");
          setjsonCat([]);
    
          getCat().then((response) => {
            setjsonCat(response);
          });
        } catch (e) {
          console.log(e);
        }
      };
    
 const CarousalLoop = (props) => {
            const BANNER_Hs = 1;
        
            if (jsonCat.length == 0) {
              return <View></View>;
            }
         
            const listItemstest = jsonCat.map((link) => {
              console.log(link.name);
              <View>
                <Text style={{ color: "red" }}>{link.name}</Text>
              </View>;
            });
            return (
              <View style={{ height: 220, backgroundColor: "brown" }}>
                {listItemstest}
              </View>
            );
          };

最后我的渲染组件有

{jsonCat.length ? <CarousalLoop /> : <ActivityIndicator />}

当我运行此代码时,会显示活动指示器,直到获取 API 请求,然后也正确接收到 json,console.log(link.name) 正在正确打印名称,但 CarousalLoop 显示时没有任何列表项(仅显示棕色视图组件)。

【问题讨论】:

    标签: reactjs react-native jsx


    【解决方案1】:

    你要么使用return关键字

    const listItemstest = jsonCat.map((link) => {
             console.log(link.name);
             return(
                   <View>
                    <Text style={{ color: "red" }}>{link.name}</Text>
                   </View>
                  )
                });
    

    或者用括号

          const listItemstest = jsonCat.map((link) => (
                  <View>
                    <Text style={{ color: "red" }}>{link.name}</Text>
                  </View>;
                ));
    

    【讨论】:

      【解决方案2】:

      你需要从 listItemstest 返回要渲染的项目列表,像这样。

      const listItemstest = jsonCat.map((link) => {
                    console.log(link.name);
                    return <View>
                      <Text style={{ color: "red" }}>{link.name}</Text>
                    </View>;
                  });
      

      【讨论】:

      • return 关键字很重要——没有它,你只是返回一个未定义的列表。
      猜你喜欢
      • 1970-01-01
      • 2020-06-20
      • 2020-02-07
      • 2021-06-15
      • 1970-01-01
      • 2017-12-09
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多