React Native - JSON 再次执行该功能时响应未更新

React Native - JSON reponse is not updating when doing the function again

我有一个在 flatList 中呈现的姓名列表,此列表将我带到一个详细信息页面,其中写有用户 ID。如果我再次使用菜单返回列表并选择不同的名称,相同的名称会一直出现,直到我刷新应用程序并再次执行此操作,然后选择的名字将继续存在。 ID 一直在更新,但在本例中不是“data.Name”。我怎样才能让它自己更新以便名称也改变?

App.js

function PlayersScreen( { navigation } ) {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  useEffect(() => {
  fetch('http://***.***.***.***/people',
   { credentials: "same-origin",
   headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
   },
  },
  )
    .then((response) => response.json())
    .then((json) => setData(json))
    .catch((error) => console.error(error))
    .finally(() => setLoading(false));
}, []);

  return (

         <FlatList
            data={data}
            keyExtractor={item => item.Name}
            renderItem={({ item }) => (
            <Text onPress={() => {navigation.navigate('DetailsScreen', {itemId: item._id})}}>{item.Name}</Text>
            )}
          />
  );
}

function DetailsScreen({ route, navigation }) {
  const { itemId } = route.params;
  console.log('DetailsScreen', itemId);
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  useEffect(() => {
  const apiurl = 'http://***.***.***.***:3000/people/' + itemId;
  fetch(apiurl)
  .then((response) => response.json())
  .then((responseJson) => {
    console.log(data);
   setData(responseJson)})
  .catch((error) => console.error(error))
  .finally(() => setLoading(false));
 
}, []);
     return (
    <View>
      <Text>Details Screen</Text>

      **<Text>itemId: {itemId}</Text>** <- THIS DOES CHANGE
      **<Text>{data.Name}</Text>** <- THIS DOES NOT CHANGE

      <Button title="Go back to List" onPress={() => navigation.navigate('people')} />
  );
}

我解决了。问题是在详细信息屏幕上,useEffect 没有重新渲染一次,因为 app.js 没有重新渲染。解决方案如下(取自 ReactJS 文档)

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

所以我在细节部分的最终代码看起来像这样

function DetailsScreen({ route, navigation }) {
  const { itemId } = route.params;
  console.log('DetailsScreen', itemId);
  /* 2. Get the param */
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  useEffect(() => {
  const apiurl = 'http://***.***.***.***:3000/************/' + itemId;
  console.log(apiurl)
  fetch(apiurl)
  .then((response) => response.json())
  .then((json) => setData(json))
  .catch((error) => console.error(error))
  .finally(() => setLoading(false));
}, [itemId]);

itemId 已添加到结束括号中,因此如果它发生更改,则会重新呈现。