可选链接是在React中加载API的最佳实践吗?还有其他选择吗?



下面的代码可以工作,我使用可选链接从API加载信息。我试图通过检查加载状态或检查数组是否为空来让它工作,但我没有成功。当我搜索"React API可选链接"时,我没有找到太多针对这些情况的信息。下面的代码可以工作,但是我这样做是正确的吗?还有什么其他方法可以做到这一点?最好的方法是什么?

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: true
}
}

componentDidMount() {
fetch('https://restcountries.eu/rest/v2/all')
.then(response => response.json())
.then(json => this.setState({data: json}));
this.setState({loading: false});
}


render() {
return (
<div>
<h1>{this.state.data?.length > 0 && this.state.data[0]["name"]}</h1>
</div>
)
}
}
export default App;

我认为在实际的工作场所,你的团队决定使用的方式是最好的,所以它将具体情况具体分析。

但就我个人而言,基于你这里的代码,我更喜欢这样写:

// use React Hooks
import React, { useState, useEffect } from 'react';
// Functional Components
const App = () => {
const [data, setData] = useState([]);
// useEffect is pretty much the equivalent of componentDidMount if you pass an empty array as the second argument.
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('Your API Url.');
const json = await response.json();
setData(json);
} catch (error) {
console.error(error);
}
}
fetchData();
}, []);
// Conditional Operator and Optional Chaining to help conditional render.
return (
<div>
{ data?.length > 0
? <h1>{data[0]['name']}</h1>
: <div>{`Loading...`}</div>
}
</div>
)
};
export default App;

你也可以在这里阅读更多关于如何在useEffect中使用async await语法的信息。

希望这对你有帮助。

最新更新