React Native API call



如何在页面下方的代码中显示API调用的结果?

完成后的{data.payrollid}没有显示任何值。即:文本只显示"完成",后面没有值。

我返回的JSON如下。。。

{"status_code":200,"payrollid":10,"message":"Success"}

当我console.log(data(时,我可以看到fetch工作了,我也可以看到我的JSON数组。

下面是我的React本机代码

const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://www.mywebsite.ca/api/test.php')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<>
<View>
{isLoading ? <Text>Loading...</Text> : <Text>Complete {data.payrollid}</Text> }
</View>
<View style={styles.container}>
<Text>This is my new app.</Text>
<Text>Some text</Text>
<StatusBar style="auto" />
</View>
</>
);

您的代码应该如下所示:

const [isLoading, setLoading] = useState(true);
const [data, setData] = useState({});
useEffect(() => {
fetch('https://www.mywebsite.ca/api/test.php')
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<>
<View>
{isLoading ? <Text>Loading...</Text> : 
<Text>Complete{data.payrollid}.</Text>
}
</View>
<View style={styles.container}>
<Text>This is my new app.</Text>
<Text>Your Text</Text>
<StatusBar style="auto" />
</View>
</>
);

您需要将数据保存在您的数据状态中。

const [data, setData] = useState({});
useEffect(() => {
fetch('https://www.mywebsite.ca/api/test.php')
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);

既然你得到了一个对象,就把你的原始状态切换到一个对象。

最新更新