为什么react中的文本不会动态变化

问题描述 投票:0回答:1

我这里有这个代码

function Homepage() {


  
  const [name,setName] = useState('');
  const [followers,setFollower] = useState('');
  const [about,setAbout] = useState('');



  useEffect(() => {
    
    const fetchData = async () => {
        const data = await loadhomepagescript();
        console.log('User Name:', data.user_name);
        console.log('About:', data.about);
        console.log('Followers:', data.followers);

        setName(data.user_name);
        setFollower(data.about);
        setAbout(data.followers);




    };

    fetchData();


}, []);


  return (
    <View style={styles.homepage}>
    <View style={styles.uinfo}>
      <Text style={{fontWeight:'bold', textAlign: 'left'}}>{name}</Text>
      <Text style={{fontWeight:'bold', textAlign: 'left'}}>{followers}</Text>
      <Text style={{fontWeight:'bold', textAlign: 'left'}}>{about}</Text>


    </View>
    </View>
  );
}

由于某种原因,即使 data.user_name、data.about 和 data.followers console.log 正确,我也无法将它们传递给我的元素。这是为什么?

我尝试移动 useEffect 并移动视图的返回,但没有任何效果

reactjs react-native react-hooks expo
1个回答
0
投票

该问题可能是由于执行顺序造成的。由于

useEffect
是异步的,因此可能需要一些时间来获取数据。 因此,如果组件在数据可用之前渲染,则将显示初始空状态值。

只有当数据可用时,您才能有条件地渲染组件,如下所示。

return (
  <View style={styles.homepage}>
    {name && followers && about && (
      <View style={styles.uinfo}>
        <Text style={{ fontWeight: 'bold', textAlign: 'left' }}>{name}</Text>
        <Text style={{ fontWeight: 'bold', textAlign: 'left' }}>{followers}</Text>
        <Text style={{ fontWeight: 'bold', textAlign: 'left' }}>{about}</Text>
      </View>
    )}
  </View>
);
© www.soinside.com 2019 - 2024. All rights reserved.